Java TreeMap Comparator

You can not sort TreeMap on values. A Red-Black tree based NavigableMap implementation. The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used You will need to provide comparator for Comparator<? super K> so your comparator should compare … Read more

comparing and thenComparing gives compile error

Java needs to know a type of all variables. In many lambdas it can infer a type, but in your first code snippet, it cannot guess the type of s. I think the standard way to solve that problem would be to declare it explicitly: Comparator<String> c = Comparator.comparing((String s) -> s.split(“\\s+”)[0]) .thenComparingInt(s -> Integer.parseInt(s.split(“\\s+”)[1])); … Read more

Reverse a comparator in Java 8

You can use Comparator.reverseOrder() to have a comparator giving the reverse of the natural ordering. If you want to reverse the ordering of an existing comparator, you can use Comparator.reversed(). Sample code: Stream.of(1, 4, 2, 5) .sorted(Comparator.reverseOrder()); // stream is now [5, 4, 2, 1] Stream.of(“foo”, “test”, “a”) .sorted(Comparator.comparingInt(String::length).reversed()); // stream is now [test, foo, … Read more

Android-java- How to sort a list of objects by a certain value within the object

Follow this code to sort any ArrayList Collections.sort(myList, new Comparator<EmployeeClass>(){ public int compare(EmployeeClass obj1, EmployeeClass obj2) { // ## Ascending order return obj1.firstName.compareToIgnoreCase(obj2.firstName); // To compare string values // return Integer.valueOf(obj1.empId).compareTo(Integer.valueOf(obj2.empId)); // To compare integer values // ## Descending order // return obj2.firstName.compareToIgnoreCase(obj1.firstName); // To compare string values // return Integer.valueOf(obj2.empId).compareTo(Integer.valueOf(obj1.empId)); // To compare integer … Read more

Why does PriorityQueue.toString return the wrong element order? [duplicate]

You need to poll the items from the PriorityQueue one by one. toString doesn’t do that. So instead of your System.out.println(queue); do this: while(!queue.isEmpty()) { System.out.println(queue.poll()); } The reason is that the PriorityQueue is never completely sorted internally, lookup how a heap works for more detail. Polling items from it fixes the heap during the … Read more