Find only repeated String attributes in list with Java 8

  • A+

I know below is the code to find out the occurrence of each String attributes in list , how can I filter this list with only duplicates item i.e having more than 1 occurrence. Sorry I am new to java 8 .

Map<String, Long> result =             .collect(Collectors.groupingBy(Function.identity(),                                               Collectors.counting())); 


create a stream from the entrySet and filter:

List<Map.Entry<String, Long>> result =                    .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))                    .entrySet()                    .stream()                    .filter(s -> s.getValue() >= 2)                    .collect(Collectors.toList()); 

or if you want to maintain a map then:

Map<String, Long> result = stringList().stream()                 .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))                 .entrySet()                 .stream()                 .filter(s -> s.getValue() >= 2)                 .collect(toMap(Map.Entry::getKey, Map.Entry::getValue)); 

on another note, if you just want the individual numbers that have more than or equal to 2 occurrences then you can do:

List<String> result =                 .collect(Collectors.groupingBy(Function.identity(),                         Collectors.counting()))                 .entrySet()                 .stream()                 .filter(x -> x.getValue() >= 2)                 .map(Map.Entry::getKey)                 .collect(toList()); 

another option being:

List<String> result =               .filter(x -> == 2)              .distinct()              .collect(toList()); 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: