Search results
Mar 20, 2022 · As far as I understand Comparator is a functional interface used to compare 2 objects with int compare(T o1, T o2) as the abstract function that takes two argument. but there is also a function Comparator.comparing(s->s) that can take a lambda function with only one input parameter. for Example to sort a Collection using streams.
return Comparator .comparing(Teacher::getAge); But how do I compare Lecture's on nested fields, like this? ...
Comparator<Person> comparator = Comparator.comparing(person -> person.name); comparator = comparator.thenComparing(Comparator.comparing(person -> person.age)); Check out the link above for a neater way and an explanation about how Java's type inference makes it a bit more clunky to define compared to LINQ.
Oct 7, 2015 · The line looks like this: .sorted(Comparator.comparing(Map.Entry::getValue).reversed()). For some reason the IDE starts to underline the very same parameter of comparing() (it didn't when I wasn't invoking reversed() ) and says "Non-static method cannot be referenced from a static context" 🤔
If you are using Java 8 then it's better to use below code like this: Comparator<People> comparator = Comparator.comparing(People::getName); And then simply use: Collections.sort(list, comparator); If you are using Java 7 or below then you can use a comparator for customized sorting order by implementing compare method.
I want to sort my objects in descending order using comparator. class Person { private int age; } Here I want to sort a array of Person objects.
Sep 4, 2017 · Comparator<T> c = Comparator.comparing(byCriteria); } You should also pass the List to that method that you want to sort in this case. But then why not use Collections.sort in this case and pass the List and the Comparator in the form (for example): Collections.sort(yourList, Comparator.comparing(Employee::getXXX))
Aug 4, 2012 · This is a generic Comparator for any kind of Comparable object, not just String:. package util; import java.util.Comparator; /** * The Default Comparator for classes implementing Comparable.
Jul 28, 2018 · 14. I like to use Java 8 Comparator to sort a List of an object based on three properties. The requirement is to sort in this order - Name ascending, Age descending, City ascending. If I use reversed() on `Age it reverses previously sorted entries as well. Here is what I've tried: Comparator.comparing((Person p) -> p.getName())
Jun 14, 2019 · I have a list of entities Entity with the fields id and createdDate. I want to sort them as following: higher id first. if id null, most recent createdDate first. I've tried the following unsuccessfuly, as it throwns a NullPointerException when id is null. Comparator comp = Comparator. .nullsFirst(Comparator.comparing(e -> ((Entity) e).getId()))