【问题标题】:Java - return the key with the longest ArrayList in Hashmap<Class,ArrayList<Class>>Java - 返回 Hashmap<Class,ArrayList<Class>> 中 ArrayList 最长的键
【发布时间】:2016-07-21 17:39:26
【问题描述】:

我一直在尝试修改此处类似问题的最佳答案中的代码,但我无法让它适用于数组列表长度

Get the keys with the biggest values from a hashmap?

假设我有

HashMap&lt;Customer,ArrayList&lt;Call&gt;&gt; outgoingCalls = new HashMap&lt;Customer,ArrayList&lt;Call&gt;&gt;();

当程序运行时,它会将每次调用都存储在 hashmap 中。我想遍历这个哈希图并返回拨打最多电话的客户。我一直在尝试从上面的链接修改此代码,但我完全迷路了

   Entry<Customer,ArrayList<Call> mostCalls = null;

   for(Entry<String,ArrayList<Call> e : outgoingCalls.entrySet()) {
     if (mostCalls == null || e.getValue() > mostCalls.getValue()) {
        mostCalls = e;

【问题讨论】:

  • e.getValue() 返回一个ArrayList&lt;Call&gt;mostCalls.getValue() 也是如此。 >(大于)适用于数字,而不是像 ArrayList 这样的集合。

标签: java arraylist hashmap


【解决方案1】:

关闭,但不完全。

 Entry<Customer,ArrayList<Call>> mostCalls = null;

 for(Entry<String,ArrayList<Call>> e : outgoingCalls.entrySet()) {
   if (mostCalls == null || e.getValue().size() > mostCalls.getValue().size()) {
      mostCalls = e;
   }
 }

【讨论】:

  • 谢谢!我忘记提到的一件事是我收到了cannot find symbol: Entry 错误。我认为java.util.* 应该足以导入它,但我还需要做些什么吗?
  • 您需要import java.util.Map.Entry 或使用Map.Entry 而不是Entry
  • 完美,谢谢。我仍然需要编写代码才能实际显示它,但我没有收到任何编译器错误,我会认为这是一个好兆头。
【解决方案2】:

你可以试试这个。您将不需要任何额外的导入。

int maxSize = Integer.MIN_VALUE;
for(Customer e: outgoingCalls.keySet()) {
    if (maxSize < outgoingCalls.get(e).size()) {
        maxSize = outgoingCalls.get(e).size();
        mostCalls = e;
    }
}

【讨论】:

    【解决方案3】:
    public class T {
        public static void main(String[] args) {
        List<Customer> customerList = new ArrayList<Customer>();
        customerList.add(new Customer());
        Collections.sort(customerList, new Comparator<Customer>() {
            @Override
            public int compare(Customer c1, Customer c2) {
            return c1.callsMadeByCustomer.size() - c2.callsMadeByCustomer.size();
            }
        });
        System.out.println("Most Calls: " + customerList.get(customerList.size() - 1));
        }
    }
    
    class Customer {
        ArrayList<Call> callsMadeByCustomer;
    
        public Customer() {
            callsMadeByCustomer = new ArrayList<Call>();
        }
    }
    

    你甚至可以像这样组织它。所以现在callsMadeByCustomer 在customer 类中。

    【讨论】:

      猜你喜欢
      • 2016-08-27
      • 2016-09-12
      • 2016-08-28
      • 2020-04-30
      • 2020-03-25
      • 1970-01-01
      • 1970-01-01
      • 2012-05-27
      • 1970-01-01
      相关资源
      最近更新 更多