Collections framework in Java

Collections is nothing but the group of Objects.

In Java, collection framework is made up of below classes and interfaces. Important interfaces in Collection framework are given below.

  1. List – stores all types of values
  2. Set – stores only unique values
  3. Queue – stores values in Queue data structure
  4. Map – Stores key-value pairs

Important concrete classes that implement above interfaces are given below.

  1. ArrayList, LinkedList, Vector, Stack
  2. HashSet, TreeSet, LinkedHashSet
  3. PriorityQueue, ArrayDeque
  4. HashMap, TreeMap, LinkedHashMap, HashTable, SortedMap
  5. Collections – provides some static methods (algorithms) to work with any collection type
  6. Iterable – This interface is used for iterating through elements in the collection object

Below image shows various classes and interfaces hierarchy of collections framework in Java.

Interfaces & Classes in Java Collections Framework

Interfaces & Classes in Java Collections Framework

Below image helps us to understand which collection class should be used and when.

Collections in Java

When and How to use Collections

Here is an example ArrayList.

package corejava;

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

/**
 * Created by Sagar on 10-04-2016.
 */
public class collections {

    public static void main(String [] args){
        List<String> myList = new ArrayList<String>();
        myList.add("Brisbane");
        myList.add("Paris");
        myList.add("chicago");
        myList.add("London");
        Collections.sort(myList);

        //Iterating using new for loop
        for (String x : myList){
            System.out.println(x);
        }

        myList.remove("Paris");
        System.out.println("*********After removing Paris*********");
        //Iterating using Itr class
        Iterator<String> iter = myList.iterator();
        while (iter.hasNext()) {
            String str = iter.next();
            System.out.println(str);
        }
        System.out.println("List size is -> " + myList.size());
        System.out.println("List contains London? -> " + myList.contains("London"));

        //Iterating using Lambda expressions in Java 8
        myList.forEach( value -> System.out.println(value));

    }
}

Here is the output of the above code.
Brisbane
London
Paris
chicago
*********After removing Paris*********
Brisbane
London
chicago
List size is -> 3
List contains London? -> true
Brisbane
London
chicago

Process finished with exit code 0

You may also like...