Sort two object using Comparator

Sort two object using Comparator

Answer: Below is sample java code where sorting has been done on Integer value using Comparator interface:

package com.javahonk;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class ComparatorTest {
    static Boolean ascending = false;

    public static void main(String[] args) {

        List<Integer> numberList = new ArrayList<Integer>();
        numberList.add(1);
        numberList.add(4);
        numberList.add(3);
        numberList.add(5);
        numberList.add(2);

        System.out.println("Unsorted list: " + numberList);
        // Sort list in descending order
        Collections.sort(numberList, new SortingTest());

        System.out.println("\nSorted list descending order: " + numberList);

        // Sort list in ascending order:
        SortingTest.ascending = true;
        Collections.sort(numberList, new SortingTest());
        System.out.println("\nSorted list ascending order: " + numberList);
    }

}

class SortingTest implements Comparator<Integer> {

    public static boolean ascending;

    @Override
    public int compare(Integer o1, Integer o2) {
        if (ascending) {
            return o1.intValue() - o2.intValue();
        } else {
            return o2.intValue() - o1.intValue();
        }
    }

}

Output:

Sort two object using Comparator

Leave a Reply

Your email address will not be published. Required fields are marked *

I am not Robot *