0

In Java, I have for example the following list:

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

And I want to pick those repeated and show only one with the number of repetitions.

Output:

jack
john (x2)
rick (x3)

3 Answers3

3

Using stream():

Map<String, Long> map = testList.stream()
    .collect(Collectors.groupingBy(s -> s.toString(), Collectors.counting()));
J.F.
  • 13,927
  • 9
  • 27
  • 65
3

Count the frequencies using Stream API (Collectors.groupingBy + Collectors.counting) and print the entries of the map using its forEach method:

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) : "")
        ));
Nowhere Man
  • 19,170
  • 9
  • 17
  • 42
1

You can simply use a HashMap to store the count of each word.

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());
}
Laurel
  • 5,965
  • 14
  • 31
  • 57