Sort ArrayList user defined objects

Sort ArrayList user defined objects

Answer: Below java class will show you how to sort an ArrayList of user defined objects. It shows both ascending and descending order sorting:

package com.javahonk;

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

public class SortArrayList {

    public static void main(String[] args) {
        
        List<String> list = new ArrayList<String>();
        list.add("D");
        list.add("C");
        list.add("A");
        list.add("B");
        list.add("Java Honk");
        list.add("E");
        list.add("G");
        list.add("F");
        list.add("H");
        
        System.out.println("Sorting in ascending order");
        Collections.sort(list);
        
        for (String string : list) {
            System.out.println(string);
        }
        
        System.out.println("\nSorting in decending order");
        Collections.sort(list, new SortComparator());
        
        for (String string : list) {
            System.out.println(string);
        }

    }   

}

class SortComparator implements Comparator<String> {

    @Override
    public int compare(String o1, String o2) {
        
        if (o2.compareTo(o1) > 0) {
            return 1;
        } else if (o2.compareTo(o1) == 0){
            return 0;
        }else {
            return -1;
        }
        
    }   

}


Output:

Below java class will show you how to sort an ArrayList of user defined objects. It shows both ascending and descending order sorting:

Leave a Reply

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