计算 ArrayList 中项目的出现次数并列出前 N 个项目

Count the occurrences of items in ArrayList and list top N items

场景:

作为这个 question 的后续,我有一个 java.util.ArrayList<Parcel> 和一个 Parcel 对象。

public class Parcel {
    /** The name. */
    private String name;

    /** The address. */
    private String address;

    /** The contact no. */
    private String contactNo;

    /** The postal code. */
    private String postalCode;

    // Accessors and mutators
} 

我有一个方法returns InputStream 的包裹列表。

List<Parcel> parcels = parcelManager.getParcelList(inputStream);


@Test
public void testParcelBeanReturnCount() {
   Assert.assertEquals(13, tester.getParcelList(inputStream)); // works fine.
}

现在,如何列出前 N 个邮政编码以及递送的包裹数量(到特定邮政编码)?我尝试使用 Guava 的 Multiset API。

Multiset<Parcel> postalCodeCount = HashMultiset.create(parcels);

System.out.println(postalCodeCount.size()); // 13.

Class Parcel 需要明确定义 hashCode()equals().

HashCode and Equals method in Java object

或者,您可以使用 Java8:

List l = parcels.stream()
         .collect(Collectors.groupingBy(p -> p.getPostalCode()))
         .entrySet()
         .stream()
         .sorted((e1, e2) -> Integer.compare(e2.getValue().size(), e1.getValue().size()))
         .limit(N) //Top N
         .collect(Collectors.toList());