Lets say that I have an java object with multiple String fields.
public class Person {
private String field1
// keeps going
I want to be able to have the ability to sort a list of persons depending on whatever field I choose.
I know that I can use the comparator interface and implement multiple compareTo's as described in the topic: How do I make 2 comparable methods in only one class?
But while using Collections.sort()
But is there some way for me to do this without all this repeating code?
If you don't like the verbosity of Comparator classes, then use Java 8 and its lambda expressions:
Comparator<Person> byName = Comparator.comparing(Person::getName);
Comparator<Person> byBirthDate = Comparator.comparing(Person::getBirthDate);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With