Find the most common String in ArrayList()

后端 未结 12 935
无人及你
无人及你 2020-12-08 16:59

Is there a way to find the most common String in an ArrayList?

ArrayList list = new ArrayList<>();
list.add(\"t         


        
12条回答
  •  借酒劲吻你
    2020-12-08 17:53

    You can use Guava's Multiset:

    ArrayList names = ...
    
    // count names 
    HashMultiset namesCounts = HashMultiset.create(names);
    Set> namesAndCounts = namesCounts.entrySet();
    
    // find one most common
    Multiset.Entry maxNameByCount = Collections.max(namesAndCounts, Comparator.comparing(Multiset.Entry::getCount));
    
    // pick all with the same number of occurrences
    List mostCommonNames = new ArrayList<>();
    for (Multiset.Entry nameAndCount : namesAndCounts) {
        if (nameAndCount.getCount() == maxNameByCount.getCount()) {
            mostCommonNames.add(nameAndCount.getElement());
        }
    }
    

提交回复
热议问题