Home > other >  JAVA custom sort ArrayList based on multiple object property [duplicate]
JAVA custom sort ArrayList based on multiple object property [duplicate]

Time:09-22

I have an ArrayList of custom object Friend, I would like to sort it based on multiple object property conditions.

ArrayList<Friend> friends;
public class Friend {
    int age;
    String name;
}
  1. Sort the list based on age (high to low).
  2. If age is the same, sort based on name (alphabetical).

Example:

Friend(10, "a");
Friend(4, "b");
Friend(5, "d");
Friend(5, "c");
Friend(1, "e");

Output:

Friend(10, "a");
Friend(5, "c");
Friend(5, "d");
Friend(4, "b");
Friend(1, "e");

CodePudding user response:

Implement Comparable<Friend> to Friend class and write a compareTo method in Friend Class as follows

public int compareTo(Friend frnd){
       int n =  (getAge() - frnd.getAge());
       if ( n == 0 )
           n = getName().compareTo(frnd.getName());
       return n;
}

CodePudding user response:

You can implement Friend using : Comparable

The code will be something like :

public class Friend implements Comparable<Friend> {
int age;
String name;

@Override
public int compareTo(Friend o) {

    if(age != o.age)
        return Integer.compare(age , o.age);

    return (name.compareTo(o.name));
}}

Then you can Collections.sort() normally

For more reference you can check also : Sort ArrayList of custom Objects by property

CodePudding user response:

You can sort the list and add 2 comparators

friends = friends.stream().sorted(Comparator.comparing(Friend::getName).thenComparing(Friend::getAge)).collect(Collectors.toList());

CodePudding user response:

This is a useful thread containing examples of arraylist objects sorting using many methods

What you looking for in that thread is Sorting ArrayList<Object> multiple properties with Comparator

It has examples on how to use interfaces like Comparable and Comparator to help you sort arraylists of objects.

  • Related