I have an arrayList of different types of players based on sports. I need to sort the list of players in the arrayList by last name to start. If 2 players have the same la
//requires java@8
//class Person { String fName; String lName; int id}
List list = new ArrayList<>();
Person p1 = new Person();
p1.setfName("a");
p1.setlName("x");
list.add(p1 );
Person p4 = new Person();
p4.setfName("b");
p4.setlName("z");
list.add(p4);
Person p3 = new Person();
p3.setfName("a");
p3.setlName("z");
list.add(p3);
Person p2 = new Person();
p2.setfName("a");
p2.setlName("y");
list.add(p2);
//sort by a single field
Collections.sort(list, (o1,o2) -> o1.getfName().compareTo(o2.getfName()));
//sort by multiple cascading comparator.
Collections.sort(list, Comparator.comparing(Person::getfName).thenComparing(Person::getlName));
list.forEach( System.out::println);
//output
//Person [fName=a, lName=x, id=null]
//Person [fName=a, lName=y, id=null]
//Person [fName=a, lName=z, id=null]
//Person [fName=b, lName=z, id=null]