Difference between Comparable and Comparator

Comparable Comparator
1) Comparable provides single sorting sequence. In other words, we can sort the collection on the basis of single element such as id or name or price etc. Comparator provides multiple sorting sequence. In other words, we can sort the collection on the basis of multiple elements such as id, name and price etc.
2) Comparable affects the original class i.e. actual class is modified. Comparator doesn’t affect the original class i.e. actual class is not modified.
3) Comparable provides compareTo() method to sort elements. Comparator provides compare() method to sort elements.
4) Comparable is found in java.lang package. Comparator is found in java.util package.
5) We can sort the list elements of Comparable type byCollections.sort(List) method. We can sort the list elements of Comparator type byCollections.sort(List,Comparator) method.

Adding values in ArrayList

import java.util.ArrayList;
import java.util.List;

public class TestArrayList{

	public static void main(String[] args) {
		String name1 = "Rajan";
		String name2 = "karthik";
		String name3 = "Vimal";
                //Declaration and Construction of Array List 
		List<String> nameList = new ArrayList<String>();
                //Adding String Object in Array List
		nameList.add(name1);
		nameList.add(name2);
		nameList.add(name3);

		System.out.println("Names in the list are");
                
		for(String name:nameList)
		{
			System.out.println(name);
		}

	}
}

Sort an ArrayList Element

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
 
public class SortCollection {
 
	public static void main(String... args)
	{
 
		List<String> li = new ArrayList<String>();

		li.add("India");
		li.add("United States");
		li.add("Malaysia");
		li.add("Australia");
		li.add("Lundon");

		Collections.sort(li);
		System.out.println("Countries are: ");
		for(String temp: li)
		{
			System.out.println(temp);
		}
		
	}
}

Priority Queue

package com.sridhar.queue;
import java.util.Comparator;
import java.util.PriorityQueue;
public class TestPriorityQueueOperations {
     
    public static class PQSort implements Comparator<Integer>{
        @Override
        public int compare(Integer o1, Integer o2) {
            // TODO Auto-generated method stub
            return o2-o1;
        }
         
         
    }
    public static void main(String[] args)
    {
        int[] intArray = {4,3,8,2,7,1,5};
         
        //Creating Priority Queue object with natural ordering
        PriorityQueue<Integer> objLowPq = new PriorityQueue<Integer>();
         
        //Adding values into queue
        for(int x: intArray)
        {
            objLowPq.offer(x);
        }
         
        //checking size of the queue
        System.out.println("size of queue="+objLowPq.size());
         
        //To see the element based on the priority
        System.out.println("Element stored in queue="+objLowPq.peek());
        System.out.println("size of queue="+objLowPq.size());
         
        //To remove the element from the queue based on the priority
        System.out.println("Element removed from the queue ="+objLowPq.poll());
         
        //removing all elements from the queue
        System.out.println("\nRemoving Elements from objLowPq");
        removeAllElements(objLowPq);
         
        //Creating Priority Queue object with custom order
        PQSort objPqs= new PQSort();
        PriorityQueue<Integer> objHighPq = new PriorityQueue<Integer>(objPqs);
             
        //Adding elements into Queue
        for(int x: intArray)
        {
            objHighPq.offer(x);
        }
         
        //checking size of the queue
        System.out.println("\nsize of queue="+objHighPq.size());
                 
        //removing all elements from the queue
        System.out.println("\n\nRemoving Elements from objHighPq");
        removeAllElements(objHighPq);
                 
    }
     
    static void removeAllElements(PriorityQueue<Integer> objTempPQ)
    {
        int queSize=objTempPQ.size();
        System.out.print("Elements removed:");
        for(int i=0;i<queSize;i++)
        {
            System.out.print(objTempPQ.poll()+" ");
        }
    }
}

Map Operations

package com.sridhar.collections;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
public class TestMapInterface {
public static void main(String[] args) {
 
    //Step 1: Creating a Map
    //Specify What kind of values to store in map by using generics
    Map&lt;String,String&gt; studentMap = new TreeMap&lt;String,String&gt;();
 
    //Step 2: Putting values into the Map
 
    studentMap.put(&quot;08ECR001&quot;, &quot;Arun&quot;);
    studentMap.put(&quot;08ECR002&quot;, &quot;Bala&quot;);
    studentMap.put(&quot;08ECR003&quot;, &quot;Chitra&quot;);
    studentMap.put(&quot;08ECR006&quot;, &quot;Elango&quot;);
    studentMap.put(&quot;08ECR004&quot;, &quot;David&quot;);
    studentMap.put(&quot;08ECR005&quot;, &quot;Farana&quot;);
 
    //Step 3: Print the values
    System.out.println(studentMap);
 
    //Operations
 
 
    //Contains - Check for a value present or not
    //Check the key in a collection
    if(studentMap.containsKey(&quot;08ECR003&quot;))
    {
        System.out.println(&quot;Yes; 08ECR003 is Present&quot;);
    }
    else
    {
        System.out.println(&quot;Nope!&quot;);
    }
 
 
    //Check the values in a collection
    if(studentMap.containsValue(&quot;David&quot;))
    {
        System.out.println(&quot;Yes; David is Present&quot;);
    }
    else
    {
        System.out.println(&quot;Nope!&quot;);
    }
 
 
 
    //Get the values for the given key, if it is not present then it will return null (but the key can not be an index)
     
    System.out.println(&quot;The value of 08ECR009 is &quot;+studentMap.get(&quot;08ECR009&quot;));
 
    //Removing objects from the collection
    studentMap.remove(&quot;08ECR003&quot;);
    System.out.println(&quot;08ECR003 is removed from the map&quot;);
 
    //Size of the map
    System.out.println(&quot;Now the size of the map is: &quot;+ studentMap.size());
 
 
    System.out.println(&quot;Values listed after conversion of Map to Set&quot;);
    //Iterating a map - Map i be iterated instead of this we can convert those values in to another collections
 
    //converting map to set
    Set&lt;String&gt; keySet = studentMap.keySet();//returning group of keys
    for(String key: keySet)
    {
        System.out.println(key + &quot;,&quot;+studentMap.get(key));
    }
 
 
    //Converting map to collections to retrieve values
    System.out.println(&quot;Values listed after conversion of Map to Collection&quot;);
    Collection&lt;String&gt; listValues= studentMap.values();
    for(String values: listValues)
    {
        System.out.println(values);
    }
 
 
    System.out.println(&quot;Values listed by converting Map to Entry&quot;);
    //Entryset - its a cloning of set &amp; a map; has both keys and values
    Set&lt;Entry&lt;String, String&gt;&gt; studentMapSet = studentMap.entrySet();
 
    Iterator&lt;Entry&lt;String, String&gt;&gt; studentMapSetIr = studentMapSet.iterator();
    while(studentMapSetIr.hasNext())
    {
        //Data that goes in(entryset()) and comes out(Entry) of an entryset is of type entry object
        Entry entryData = (Entry)studentMapSetIr.next();
        System.out.println(entryData.getKey()+&quot; &quot;+entryData.getValue());
    }
 
    //Clears the Map data
    studentMap.clear();
    }
}

Introduction to Collection

What can we do with collections?

There are a few basic operations you’ll normally use with collections:

  • Add objects to the collection.
  • Remove objects from the collection.
  • Find out if an object (or group of objects) is in the collection.
  • Retrieve an object from the collection without removing it.
  • Iterate through the collection, looking at each element (object) one after another.

 

Key Interfaces and Classes of the Collections Framework:

Three different collections in java:

  • collection (lowercase c), which represents any of the data structures in which objects are stored and iterated over.
  • Collection (capital C ), which is actually the java.util.Collection interface from which Set, List, and Queue extend. (That’s right, extend, not implement. There are no direct implementations of Collection.)
  • Collections (capital C and ends with s) is the java.util.Collections class that holds a pile of static utility methods for use with collections.

The interface and class hierarchy for collections:

List Interface:

ArrayList:

  • It is a growable array.
  • It gives you fast iteration and fast random access.
  • It is an ordered collection (by index), but not sorted.
  • Not suitable; when we do a lot of insertion and deletion.

Vector

  • A Vector is basically the same as an ArrayList, but Vector methods are synchronized for thread safety.

LinkedList

  • A LinkedList is ordered by index position, like an ArrayList, except that the elements are doubly linked to one another.
  • LinkedList may iterate more slowly than an ArrayList, but it’s a good choice when you need fast insertion and deletion.

Set Interface:

A Set cares about uniqueness—it doesn’t allow duplicates.

HashSet:

  • A HashSet is an unsorted, unordered Set.
  • Use this class when you want a collection with no duplicates and you don’t care about order when you iterate through it.

LinkedHashSet:

  • A LinkedHashSet is an ordered version of HashSet that maintains a doubly linked List across all elements.
  • Use this class instead of HashSet when you care about the iteration order.

TreeSet:

  • The TreeSet is a sorted collection.
  • It uses a Red-Black tree structure (but you knew that), and guarantees that the elements will be in ascending order, according to natural order.

 

Map Interface

A Map cares about unique identifiers.

HashMap:

    • The HashMap gives you an unsorted, unordered Map.
    • Use this class, when you need a Map and you don’t care about the order when you iterate through it.
    • the keys land in the Map is based on the key’s hashcode, so, like HashSet, the more efficient your hashCode() implementation
    • HashMap allows one null key and multiple null values in a collection.

Hashtable:

    • Hashtable is the synchronized counterpart to HashMap.
    • Hashtable doesn’t have anything that’s null.

LinkedHashMap:

    • Like its Set counterpart, LinkedHashSet, the LinkedHashMap collection maintains insertion order
    • It will be somewhat slower than HashMap for adding and removing elements, but you can expect faster iteration with a LinkedHashMap.

TreeMap:

    • TreeMap is a sorted Map “sorted by the natural order of the elements.”

Queue Interface:

PriorityQueue

    • The purpose of a PriorityQueue is to create a “priority-in, priority out” queue as opposed to a typical FIFO queue.
    • A PriorityQueue’s elements are ordered either by natural ordering or according to a Comparator.

Simple representation of Collection implementation:

Class

Ordered

Sorted

List Collections

ArrayList By index No
Vector By index No
LinkedList By index No

Set Collections

HashSet No No
TreeSet Sorted By natural order or custom comparison order
LinkedHashSet By insertion order No

Queue

PriorityQueue Sorted By to-do order

Map

HashMap No No
Hashtable No No
TreeMap Sorted By natural order or custom comparison order
LinkedHashMap By insertion order or last access order No

Key Methods of List Interface:

S.No

Methods with Description

1 void add(int index, Object obj)

Inserts obj into the invoking list at the index passed in index. Any pre-existing elements at or beyond the point of insertion are shifted up. Thus, no elements are overwritten.

2 boolean addAll(int index, Collection c)

Inserts all elements of c into the invoking list at the index passed in index. Any pre-existing elements at or beyond the point of insertion are shifted up. Thus, no elements are overwritten. Returns true if the invoking list changes and returns false otherwise.

3 Object get(int index)

Returns the object stored at the specified index within the invoking collection.

4 int indexOf(Object obj)

Returns the index of the first instance of obj in the invoking list. If obj is not an element of the list, .1 is returned.

5 int lastIndexOf(Object obj)

Returns the index of the last instance of obj in the invoking list. If obj is not an element of the list, .1 is returned.

6 ListIterator listIterator( )

Returns an iterator to the start of the invoking list.

7 ListIterator listIterator(int index)

Returns an iterator to the invoking list that begins at the specified index.

8 Object remove(int index)

Removes the element at position index from the invoking list and returns the deleted element. The resulting list is compacted. That is, the indexes of subsequent elements are decremented by one

9 Object set(int index, Object obj)

Assigns obj to the location specified by index within the invoking list.

10 List subList(int start, int end)

Returns a list that includes elements from start to end.1 in the invoking list. Elements in the returned list are also referenced by the invoking object.

 

Key Methods of Set Interface:

 

S.No

Methods with Description

1 add( )

Adds an object to the collection

2 clear( )

Removes all objects from the collection

3 contains( )

Returns true if a specified object is an element within the collection

4 isEmpty( )

Returns true if the collection has no elements

5 iterator( )

Returns an Iterator object for the collection which may be used to retrieve an object

6 remove( )

Removes a specified object from the collection

7 size( )

Returns the number of elements in the collection

 

 

 

Key Methods of Map Interface:

S.No

Methods with Description

1 void clear( )

Removes all key/value pairs from the invoking map.

2 boolean containsKey(Object k)

Returns true if the invoking map contains k as a key. Otherwise, returns false.

3 boolean containsValue(Object v)

Returns true if the map contains v as a value. Otherwise, returns false

4 Set entrySet( )

Returns a Set that contains the entries in the map. The set contains objects of type Map.Entry. This method provides a set-view of the invoking map.

5 boolean equals(Object obj)

Returns true if obj is a Map and contains the same entries. Otherwise, returns false.

6 Object get(Object k)

Returns the value associated with the key k.

7 int hashCode( )

Returns the hash code for the invoking map.

8 boolean isEmpty( )

Returns true if the invoking map is empty. Otherwise, returns false.

9 Set keySet( )

Returns a Set that contains the keys in the invoking map. This method provides a set-view of the keys in the invoking map.

10 Object put(Object k, Object v)

Puts an entry in the invoking map, overwriting any previous value associated with the key. The key and value are k and v, respectively. Returns null if the key did not already exist. Otherwise, the previous value linked to the key is returned.

11 void putAll(Map m)

Puts all the entries from m into this map.

12 Object remove(Object k)

Removes the entry whose key equals k.

13 int size( )

Returns the number of key/value pairs in the map.

14 Collection values( )

Returns a collection containing the values in the map. This method provides a collection-view of the values in the map.

 

Key Methods of Queue Interface:

S.No
Method & description
1 add(E e)

Inserts the specified element into this priority queue.
2 clear()

Removes all of the elements from this priority queue.
3 comparator()

Returns the comparator used to order the elements in this queue, or null if this queue is sorted according to the natural ordering of its elements.
4 contains(Object o)

Returns true if this queue contains the specified element.
5 iterator()

Returns an iterator over the elements in this queue.
6 offer(E e)

Inserts the specified element into this priority queue.
7 peek()

Retrieves, but does not remove, the head of this queue, or returns null if this queue is empty.
8 poll()

Retrieves and removes the head of this queue, or returns null if this queue is empty.
9 remove(Object o)

Removes a single instance of the specified element from this queue, if it is present.
10 size()

Returns the number of elements in this collection.
11 spliterator()

Creates a late-binding and fail-fast Spliterator over the elements in this queue.
12 toArray()

Returns an array containing all of the elements in this queue.
13 toArray(T[] a)

Returns an array containing all of the elements in this queue; the runtime type of the returned array is that of the specified array.

 

Finding max and min from the collection

CollectionsUtil.java


package com.sridhar.collection;
import java.util.ArrayList;
import java.util.Collections;
public class CollectionsUtil {
    public static void main(String[] args) {
        ArrayList<Integer> intArray = new ArrayList<Integer>();

        //Adding values in to a list
        intArray.add(3);
        intArray.add(4);
        intArray.add(7);
        intArray.add(1);
        intArray.add(2);

        System.out.println("Values stored in the list are:"+ intArray);
        System.out.println("Maximum Value in the list is:"+ Collections.max(intArray));
        System.out.println("Minimum Value in the list is:"+ Collections.min(intArray));

        //Sorting a list
        Collections.sort(intArray);
        System.out.println("Values in the list after sort are:"+intArray);

        //Searching an item
        System.out.println("Index position of the value 4 is:"+Collections.binarySearch(intArray, 4));

    }
}

Decimal Object Sorting by Comparator Interface

DecimalComparator.java


package com.sridhar.collections;
import java.util.Comparator;
public class DecimalComparator implements Comparator<Double> {
    @Override
    public int compare(Double o1, Double o2) {
        // TODO Auto-generated method stub
        if (o1 < o2) { 
            return -1;           
        }           
        if (o1 > o2) {
            return 1;
        }
        return 0;
    }
}

TestDecimalCollectionSorting.java


package com.sridhar.collections;
import java.util.ArrayList;
import java.util.Collections;
public class TestDecimalCollectionSorting {
    public static void main(String[] args) {
        //ArrayList Creation
        ArrayList<Double> decimalArray = new ArrayList<Double>();

        //Adding decimal values in to ArrayList
        decimalArray.add(45.25);
        decimalArray.add(34.23);
        decimalArray.add(55.66);
        decimalArray.add(55.24);
        decimalArray.add(12.34);

        //Printing Values before sorting
        System.out.println("Before Sorting");
        System.out.println(decimalArray);

        //Creating DecimalComparator object for passing into sort method
        DecimalComparator objDC = new DecimalComparator();
        //Calling sort method to sort the decimal array
        Collections.sort(decimalArray, objDC);

        //Printing Values after sorting
        System.out.println("After Sorting");
        System.out.println(decimalArray);
    }
}

Comparator Interface – Example

Employee.java


package com.spinteam.collections;
public class Employee implements Comparable<Employee>{
    private int id;
    private String name;
    private int age;
    public Employee(int id, String name, int age) {
        super();
        this.id = id;
        this.name = name;
        this.age = age;
    }
    public Employee() {
        // TODO Auto-generated constructor stub
        super();
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }

    // To sort an values by name
    @Override
    public int compareTo(Employee o) {
        // TODO Auto-generated method stub
        return name.compareTo(o.getName());
    }

}

AgeComparator.java


package ListInterface;
import java.util.Comparator;
public class AgeComparator implements Comparator<Employee> {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
    }
    @Override
    public int compare(Employee o1, Employee o2) {
        // TODO Auto-generated method stub
        return o1.getAge()- o2.getAge();

    }
}

TestComparatorInterface.java


package com.spinteam.collections;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
public class TestComparatorInterface {
    public static void main(String[] args) {
        ArrayList<Employee> employeeList = new ArrayList<Employee>();
        Employee objEmp1 = new Employee();
        //Initializing the properties with setter methods
        objEmp1.setId(101);
        objEmp1.setName("Karthi");
        objEmp1.setAge(30);

        //Initializing the properties with constructor
        Employee objEmp2 = new Employee(102, "Raman", 28);
        Employee objEmp3 = new Employee(103, "Arjun", 29);
        Employee objEmp4 = new Employee(104, "Pavithra", 33);

        // Add an employee into a list
        employeeList.add(objEmp1);
        employeeList.add(objEmp2);
        employeeList.add(objEmp3);
        employeeList.add(objEmp4);

        //printing values of employee objects - Unsorted

        System.out.println("Printing values before sorting");
        printEmployees(employeeList);

        // Perform sort by name
        AgeComparator objAC = new AgeComparator();
        Collections.sort(employeeList,objAC);

        System.out.println("Printing values sorted by age");
        printEmployees(employeeList);

    }

    static void printEmployees(ArrayList<Employee> employeeList)
    {
        Iterator<Employee> empIterator = employeeList.listIterator();

        while(empIterator.hasNext())
        {
            Employee objEmp = (Employee)empIterator.next();
            System.out.println(objEmp.getId() +" "+ objEmp.getName() +" "+ objEmp.getAge());
        }
    }

}

Output:


Printing values before sorting
101 Karthi 30
102 Raman 28
103 Arjun 29
104 Pavithra 33
Printing values sorted by age
102 Raman 28
103 Arjun 29
101 Karthi 30
104 Pavithra 33

Comparable Interface – Example

Employee.java


package com.spinteam.collections;
public class Employee implements Comparable<Employee>{
    private int id;
    private String name;
    private int age;
    public Employee(int id, String name, int age) {
        super();
        this.id = id;
        this.name = name;
        this.age = age;
    }
    public Employee() {
        // TODO Auto-generated constructor stub
        super();
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }

    //To sort an Employee objects by name
    @Override
    public int compareTo(Employee o) {
        // TODO Auto-generated method stub
        return name.compareTo(o.getName());
    }

}

TestComparableInterface.java


package com.spinteam.collections;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
public class TestComparableInterface  {
        public static void main(String[] args) {

        ArrayList<Employee> employeeList = new ArrayList<Employee>();
        Employee objEmp1 = new Employee();
        //Initializing the properties with setter methods
        objEmp1.setId(101);
        objEmp1.setName("Karthi");
        objEmp1.setAge(30);

        //Initializing the properties with constructor
        Employee objEmp2 = new Employee(102, "Raman", 28);
        Employee objEmp3 = new Employee(103, "Arjun", 29);
        Employee objEmp4 = new Employee(104, "Pavithra", 33);

        // Add an employee into a list
        employeeList.add(objEmp1);
        employeeList.add(objEmp2);
        employeeList.add(objEmp3);
        employeeList.add(objEmp4);

        //printing values of employee objects - Unsorted

        System.out.println("Printing values before sorting");
        printEmployees(employeeList);

        // Perform sort by name
        Collections.sort(employeeList);

        System.out.println("Printing values sorted by name");
        printEmployees(employeeList);

    }

    static void printEmployees(ArrayList<Employee> employeeList){
        Iterator<Employee> empIterator = employeeList.listIterator();

        while(empIterator.hasNext())
        {
            Employee objEmp = (Employee)empIterator.next();
            System.out.println(objEmp.getId() +" "+ objEmp.getName() +" "+ objEmp.getAge());
        }
    }

}

output:


Printing values before sorting
101 Karthi 30
102 Raman 28
103 Arjun 29
104 Pavithra 33
Printing values sorted by name
103 Arjun 29
101 Karthi 30
104 Pavithra 33
102 Raman 28