How to select duplicate values from a list in java?

后端 未结 13 830
傲寒
傲寒 2021-01-18 00:38

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

相关标签:
13条回答
  • 2021-01-18 01:35

    again lambda saves the day:

    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]
    


    the speed-optimized version of the above solution:

    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]
    

    the long values of duplicate are not saved but counted — quite certainly the fastest and most space-saving variant

    0 讨论(0)
提交回复
热议问题