Java - 返回Hashmap中最长的ArrayList的键<class,arraylist <class>&gt;

时间:2016-04-01 19:26:48

标签: java arraylist hashmap

我一直在尝试从类似问题的顶级答案修改代码,但是我无法让它适用于arraylist长度

Get the keys with the biggest values from a hashmap?

让我说我有

HashMap<Customer,ArrayList<Call>> outgoingCalls = new HashMap<Customer,ArrayList<Call>>();

当程序运行时,它会存储在hashmap中进行的每个调用。我想运行这个hashmap并返回拨打过多电话的客户。我一直试图从上面的链接修改此代码,但我完全丢失了

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

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

3 个答案:

答案 0 :(得分:5)

关闭,但不完全。

 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;
   }
 }

答案 1 :(得分:0)

你可以尝试一下。您不需要任何额外的进口。

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

答案 2 :(得分:0)

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>();
    }
}

你甚至可以这样组织它。所以现在,callMadeByCustomer都在客户类中。