[Java] Sort using java comparator

less than 1 minute read

-You can sort conveniently by using comparator.

code (ascending sort)


import java.util.*;

class Solution {

    public static void main(String[] args) {
        sort1();
        sort2();
    }

    public static void sort1 () {
        List<Integer> list1 = Arrays.asList(3,2,8,4);
        System.out.println("before sort: "+list1);
        Comparator<Integer> comparator = new Comparator<Integer>() {
            public int compare(Integer int1, Integer int2) {
                return (int1.compareTo(int2));
            }
        };
        Collections.sort(list1, comparator);
        System.out.println("comparator (instantiate), after sort: "+list1);
    }

    public static void sort2(){
        List<Integer> list1 = Arrays.asList(3,2,8,4);
        System.out.println("before sort: "+list1);
        Collections.sort(list1, (a, b) -> Integer.compare(a, b));
        System.out.println("Lambda expression comparator, after sort: "+list1);
    }
}

Output result

Before sort: [3, 2, 8, 4]
comparator (instantiate), after sort: [2, 3, 4, 8]
Before sort: [3, 2, 8, 4]
Lambda expression after comparator, sort: [2, 3, 4, 8]