lambda 再次节省了时间:
List<Long> 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]
上述解决方案的速度优化版本:
List<Long> 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<Long>::new, (list, e) -> {
for( long n = 0; n < e.getValue(); n++ )
list.add( e.getKey() );
}, (l1, l2) -> null ) ) );
} ) ); // [6, 6, 7, 7]
的长值duplicate
不会被保存但会被计算——当然是最快和最节省空间的变体