Home » Java » java – Sort a list based on repetition values-Exceptionshub

java – Sort a list based on repetition values-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have a string list like this : {3,2,2,1,1,1,1,4,4,4} And i want sort it by number of repetition of values so that the be this {1,1,1,1,2,2,4,4,4,3} Thanks for you attenttion

How to&Answers:

You can sort the list based on repetition using Collections.frequency with Comparator.comparingInt

Comparator.comparingInt(i->Collections.frequency(list, i)).reversed()

Below is the example

    List<Integer>  list = new ArrayList<>(List.of(3,2,2,1,1,1,1,4,4,4));

    System.out.println(list);

    list.sort(Comparator.comparingInt(i->Collections.frequency(list, i)).reversed());

    System.out.println(list);  //[1, 1, 1, 1, 4, 4, 4, 2, 2, 3]

Instead of checking the frequency of each and every element in List, you can do it in other way by grouping the element and count into Map<Integer, Long> and then creating another sorted list Collections.nCopies

List<Integer> result = list.stream()
                       .collect(Collectors.groupingBy(Function.identity(),Collectors.counting()))
                       .entrySet()
                       .stream()
                       .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
                       .map(entry->Collections.nCopies(entry.getValue().intValue(), entry.getKey()))
                       .flatMap(List::stream)
                       .collect(Collectors.toList());