What is a Collection class in Java?

What is a Collection class in Java?

What is a Collection class in Java?

What is a Collection class in Java?

Collections class defines several utility methods for collection objects like sorting, searching, reversing, etc. 

Sorting elements of List 

Collections class defines the following two methods for sorting.

1 Public static void sort(List l)
  1. To sort based on default natural sorting order
  2. In this case list should compulsory contain homogenous and comparable objects otherwise we will get RuntimeException saying ClassCastException.
  3. List should not contain null otherwise we will get NullPointerException.
2 Public static void sort(List l, Comparator c)
  1. To sort based on customized sorting order.
//Demo program for sorting elements of the list according to default natural sorting order. 
package com.java4us;

import java.util.ArrayList;
import java.util.Collections;

class Test {
    public static void main(String[] args) {
        ArrayList list = new ArrayList();
        list.add("aa");
        list.add("oo");
        list.add("ee");
        list.add("qq");
        list.add("pp");
        System.out.println("Befote Sorting " + list); // Befote Sorting [aa, oo, ee, qq, pp]
        Collections.sort(list);
        System.out.println("After Sorting " + list); // After Sorting [aa, ee, oo, pp, qq]
    }
}
//Demo program to sort elements of List according to customized sorting 
package com.java4us;

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

class Test {
    public static void main(String args[]) {
        ArrayList l = new ArrayList();
        l.add(10);
        l.add(50);
        l.add(20);
        l.add(100);
        l.add(70);
        System.out.println(l); // [10, 50, 20, 100, 70]
        Collections.sort(l, new myComparator());
        System.out.println(l); // [100, 70, 50, 20, 10]
    }
}

class myComparator implements Comparator {
    public int compare(Object obj1, Object obj2) {
        Integer i1 = (Integer) obj1;
        Integer i2 = (Integer) obj2;
        return -i1.compareTo(i2);
    }
}

Leave a Reply

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

*