First count every element with groupingBy() and counting(), then keep only the entries whose count is greater than 1. This does a single counting pass, unlike calling Collections.frequency() for every element, which is O(n²).
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
public class DuplicateCounts {
public static void main(String[] args) {
List<String> names = Arrays.asList("AA", "BB", "AA", "CC", "BB", "AA");
Map<String, Long> duplicates = names.stream()
.collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting()))
.entrySet().stream()
.filter(e -> e.getValue() > 1)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
(a, b) -> a, LinkedHashMap::new));
System.out.println(duplicates);
}
}{AA=3, BB=2}
If you only need the duplicate values and not their counts, use a HashSet: names.stream().filter(n -> !seen.add(n)).collect(Collectors.toSet()). Explaining why the counting approach is O(n) while Collections.frequency() is O(n²) usually impresses interviewers.
A concise interview answer is
I first count every element with groupingBy and counting, then stream the map's entries and keep only those with a count greater than 1. That's a single O(n) counting pass, unlike calling Collections.frequency for every element, which is O(n²).
Last updated: 11 November 2026
Previous question: How do you count each word in a list of strings using Java 8 streams?
Next question: How do you use Optional in Java 8 to safely iterate over a list that may be null?