For example my list contains {4, 6, 6, 7, 7, 8} and I want final result = {6, 6, 7, 7}
One way is to loop through the list and eliminate unique values (4, 8 in this
again lambda saves the day:
List duplicates = duplicate.stream()
.collect( Collectors.collectingAndThen( Collectors.groupingBy( Function.identity() ),
map -> {
map.values().removeIf( v -> v.size() < 2 ); // eliminate unique values (4, 8 in this case)
return( map.values().stream().flatMap( List::stream ).collect( Collectors.toList() ) );
} ) ); // [6, 6, 7, 7]
the speed-optimized version of the above solution:
List duplicates = duplicate.stream().collect( Collectors.collectingAndThen(
Collectors.groupingBy( Function.identity(), Collectors.counting() ),
map -> {
map.values().removeIf( v -> v < 2 ); // eliminate unique values (4, 8 in this case)
return( map.entrySet().stream().collect( Collector.of( ArrayList::new, (list, e) -> {
for( long n = 0; n < e.getValue(); n++ )
list.add( e.getKey() );
}, (l1, l2) -> null ) ) );
} ) ); // [6, 6, 7, 7]
the long values of duplicate
are not saved but counted — quite certainly the fastest and most space-saving variant