Jay
Jay

Reputation: 9477

Java 8 stream sort by maximum duplicates and then distinct

Using a stream, how to sort a list of objects by field (in my case ,componentCode) that has the maximum number of duplicates, and then find distinct

I tried something like this, but how to add the size of the duplicates when sorting.

List<String> conflictingComponentsCode = componentWarnings.stream()
    .sorted(Comparator.comparing(ComponentErrorDetail::getComponentCode))
    .map(ComponentErrorDetail::getComponentCode)
    .distinct()
    .collect(Collectors.toList());

enter image description here

Upvotes: 2

Views: 1680

Answers (2)

nafas
nafas

Reputation: 5423

the idea is to use Collectors.groupingBy function to make a map (value to count), then sort the map in reverse order then map back to list again.

here a rough implementation:

List<String> conflictingComponentsCode = 
componentWarnings.stream()
    .map(ComponentErrorDetail::getComponentCode).collect(
        Collectors.groupingBy(
            Function.identity(), Collectors.counting())
        ) 
    //sort map
    .entrySet().stream()
        .sorted(Map.Entry.<String, Long>comparingByValue()
             .reversed())

    //map to list
   .map(entry -> entry.key()).collect(Collectors.toList());
;

Upvotes: 2

Anne
Anne

Reputation: 249

Very similar to @nafas option:

List<String> conflictingComponentsCode = componentWarnings.stream()
    .map(ComponentErrorDetail::getComponentCode)
    .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())) 
    .entrySet()
    .stream()
    .sorted(Map.Entry.<String, Long>comparingByValue().reversed())
    .map(Map.Entry::getKey)
    .collect(Collectors.toList());

You can check this question for another example of grouping by count: Group by counting in Java 8 stream API

Upvotes: 4

Related Questions