1

I have a List of object as List<Human> humanList; which human object consist of 5 variable as firstname, lastname,color,length,sex.

How can i check out to see the variable(firstname) how many times appear/exist in the list?

    List<Human> humanList = getHumanList();
    for(Human human :humanList){

    }
itro
  • 7,006
  • 27
  • 78
  • 121

3 Answers3

2

Assuming here firstname is of type String, if it is not - change it as needed.

Create a Map<String,Integer> (let it be map) which will be used as a histogram.
Iterate the list, and for each human:

Integer temp = map.get(human.firstName); //search for the current number of occurances
if (temp == null) map.put(human.firstName, 1); //first occurance of this firstname
else map.put(human.firstName,temp+1); //not first occurance, modify the map.

When you are done map holds each firstName as a key and the number of its occurances as the matching value.

amit
  • 175,853
  • 27
  • 231
  • 333
2

You can use guava multiset count method http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained.

Multiset<Human> set = HashMultiset.create();
        set.count(Human.firstName);
Yahor10
  • 2,123
  • 1
  • 13
  • 13
1

You need to traverse the list counting occurences O(N).
A better option if you need this often would be to increment a counter as you add/remove from the list and use that instead of traversing

Cratylus
  • 52,998
  • 69
  • 209
  • 339