Java sort array of objects by integer field and if those are identical then sort by another integer value

Viewed 566

I have a java problem in relation too sorting an arrayList of objects.

I have already figured out to sort an arrayList of object by specific fields, which can be seen in the following code

public void printPrioritized() {
    System.out.println("Prioritized todo:");
    System.out.println("-----------------");
    List<Task> sortedList = new ArrayList<Task>(taskList);

    Collections.sort(sortedList, new Comparator<Task>() {
        public int compare(Task o1, Task o2) {
            return Integer.valueOf(o1.getPriority()).compareTo(o2.getPriority());
        }
    });

    sortedList.forEach((e) -> {
        System.out.println(e);
    });

My problem is that if to object fields are the same then i am supposed to sort by another value. This means that i have to sort by an value of 1 to 4 (getPriority() method), but if two objects for instance both are 2 then i have to sort by another value which for instance could be time. Hope someone can help.

2 Answers

Assuming your Task class looks something like:

class Task {
    int priority;
    int anotherValue;
    // getters, setters ...
}

you can create custom compartors and chain them while sorting, example:

List<Task> myList = new ArrayList<>();

Comparator<Task> byPriority = (t1,t2) -> Integer.compare(t1.getPriority(), t2.getPriority());
Comparator<Task> byAnotherValue = (t1,t2) -> Integer.compare(t1.getAnotherValue(), t2.getAnotherValue());

myList.sort(byPriority.thenComparing(byAnotherValue));

OR you can combine those sortings ->

List<Task> myList = new ArrayList<>();

Comparator<Task> sortedComparator = (t1,t2) -> {
    if (t1.getPriority() != t2.getPriority()) {
        return Integer.compare(t1.getPriority(), t2.getPriority()); 
    }
    else if (t1.getAnotherValue() != t2.getAnotherValue()) {
        return Integer.compare(t1.getAnotherValue(), t2.getAnotherValue());
    }
};

myList.sort(sortedComparator);

Try to customize the compare method. e.g.

if(o1.getPriority() != o2.getPriority()) 
   return Integer.valueOf(o1.getPriority()).compareTo(o2.getPriority());

if(o1.getTime() != o2.getTime())
   return Integer.valueOf(o1.getTime()).compareTo(o2.getTime());

return 0; //they are equal with all fields
Related