Just curious to know on whether we can sort a List according to the frequency of repeated numbers using Java 8 without writing a Custom Comparator class.
I need to sort the given integers based on its frequency and then by the natural numerical order.
I'm getting error at Comparator.naturalOrder();
Here is the code which I tried:
Integer[] given = new Integer[]{0,0,1,22,11,22,22,11,44,555,55,66,77,88,99};
List intList = Arrays.asList(given);
Map frequencyMap = intList.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
List newList = intList.stream().sorted(Comparator.comparing(frequencyMap::get).thenComparing(Comparator.naturalOrder())).collect(Collectors.toList());
System.out.println(newList.toString());
The expected output is
[1, 44, 55, 66, 77, 88, 99, 555, 0, 0, 11, 11, 22, 22, 22]
PS: Used arrays in first line in order to avoid list.add() in multiple lines and for clear understanding.
JavaScript questions and answers, JavaScript questions pdf, JavaScript question bank, JavaScript questions and answers pdf, mcq on JavaScript pdf, JavaScript questions and solutions, JavaScript mcq Test , Interview JavaScript questions, JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)