0

I have a List<Person>. Person's attributes are String name, String secondName, int phoneNum.

How can I sort this List by the String property secondName?

I've tried moving into another List<String> the data from the previous list moving secondName to the first position, then applying Collection.sort and creating other List<Person> with the data of the List sorted but its too complicated.

Rich N
  • 8,939
  • 3
  • 26
  • 33

2 Answers2

3

Java 8 introduced a sort method in the List interface which can use a comparator.

If you have a getter for secondName you can do this:

 myList.sort(Comparator.comparing(Person::getSecondName));

If you don't have a getter use this one:

myList.sort(Comparator.comparing((person)->(person.secondName)));

for more ways and answers: link

pwdz
  • 49
  • 5
1

Lets assume here is your Pojo Class Person.

class Person{
String name;
String secondName;
//Getter and setters
}

Then sort the list by java collection API itself.

java.util.Collections.sort(personList, new Comparator<Person>() {
        @Override
        public int compare(Person o1, Person o2) {
            return o1.getSecondName().compareToIgnoreCase(o2.getSecondName());
        }
        });
Joginder Malik
  • 455
  • 5
  • 12