【问题标题】:how to count variable of a list of objects in java?如何计算java中对象列表的变量?
【发布时间】:2012-08-20 09:45:36
【问题描述】:

我有一个对象列表为List<Human> humanList; 哪个人类对象由 5 个变量组成,分别是名字、姓氏、颜色、长度、性别。

如何查看变量(名字)在列表中出现/存在的次数?

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

    }

【问题讨论】:

  • “在列表中”是什么意思?你的意思是它不为空?
  • 请澄清您的问题。目前还不清楚。
  • 我的意思是在列表中出现了多少次。

标签: java list map


【解决方案1】:

这里假设firstname 的类型为String,如果不是,请根据需要进行更改。

创建一个Map&lt;String,Integer&gt;(让它成为map),它将用作histogram
迭代列表,并针对每个人:

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 保存为键,并将其出现次数作为匹配值。

【讨论】:

    【解决方案2】:

    你可以使用guava multiset计数方法http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained

    Multiset<Human> set = HashMultiset.create();
            set.count(Human.firstName);
    

    【讨论】:

    • guava 是否存在 Maven 依赖项?
    • 是的,如果类 Human 的 equals 和 hashCode 仅基于 firstName。
    • 我得到了 maven 依赖,现在我要测试它。想一想,你的意思是什么(hashCode are based on firstName)?可以举个例子吗?
    【解决方案3】:

    您需要遍历列表计数出现O(N)
    如果您经常需要这样做,一个更好的选择是在您从列表中添加/删除时增加一个计数器并使用它而不是遍历

    【讨论】:

      猜你喜欢
      • 2021-08-03
      • 2017-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-12
      • 2014-02-26
      • 1970-01-01
      相关资源
      最近更新 更多