将列表中的重复值与重复次数合二为一

Transform repeated values from a list in one with the number of repetitions

在 Java 中,我有以下列表:

List<String> testList = Arrays.asList["jack","john","john","rick","rick","rick"]

我想挑出那些重复的,只显示一个有重复次数的。

输出:

jack
john (x2)
rick (x3)

您可以简单地使用 HashMap 来存储每个单词的计数。

HashMap<String, Integer> hs = new HashMap<>();
for (String str : testList) {
    hs.put(str, hs.getOrDefault(str, 0) + 1);
}
Iterator hmIterator = hs.entrySet().iterator();
while (hmIterator.hasNext()) {
    Map.Entry mapElement = (Map.Entry) hmIterator.next();
    System.out.println(mapElement.getKey() + " " + mapElement.getValue());
}

使用stream()

Map<String, Long> map = testList.stream()
    .collect(Collectors.groupingBy(s -> s.toString(), Collectors.counting()));

使用 Stream API (Collectors.groupingBy + Collectors.counting) 计算频率并使用其 forEach 方法打印地图的条目:

testList.stream()
        .collect(Collectors.groupingBy(
            x -> x, // or Function.identity()
            LinkedHashMap::new, // to keep insertion order
            Collectors.counting()
        )) // get LinkedHashMap<String, Long>
        .forEach((str, freq) -> System.out.println(
            str + (freq > 1 ? String.format("(x%d)", freq) : "")
        ));