Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Having multiple types of sorts for an object

Tags:

java

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?

like image 234
user1413969 Avatar asked Dec 02 '25 00:12

user1413969


1 Answers

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);
like image 64
JB Nizet Avatar answered Dec 03 '25 12:12

JB Nizet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!