EN
Java 8 - count unique String using Collectors.groupingBy
5
points
Quick solution:
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
public class CountStrings {
public static void main(String[] args) {
List<String> usernames = new ArrayList<>();
usernames.add("Kate"); // Kate - 1st time
usernames.add("John");
usernames.add("Ann");
usernames.add("Kate"); // Kate - 2nd time
usernames.add("Kate"); // Kate - 3rd time
Map<String, Long> usersToCount = usernames.stream().collect(
Collectors.groupingBy(
Function.identity(), Collectors.counting()
)
);
usersToCount.forEach(
(user, count) -> System.out.println(user + ", " + count)
);
}
}
Output:
Ann, 1
Kate, 3
John, 1