我有一个对象列表,List<Human> humanList;
其中人类对象由 5 个变量组成,分别是名字、姓氏、颜色、长度、性别。
我如何查看变量(名字)在列表中出现/存在多少次?
List<Human> humanList = getHumanList();
for(Human human :humanList){
}
假设这里firstname
是 type String
,如果不是 - 根据需要更改它。
创建一个Map<String,Integer>
(让它成为map
)将用作直方图。
迭代列表,并为每个人:
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.
完成后,map
将每个firstName
作为键,并将其出现的次数作为匹配值。
您可以使用 guava 多集计数方法http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained。
Multiset<Human> set = HashMultiset.create();
set.count(Human.firstName);
您需要遍历列表计数出现O(N)
。
如果您经常需要,一个更好的选择是在您从列表中添加/删除时增加一个计数器并使用它而不是遍历