Java Collections Framework

This is a short guide to using the Java Collections Framework.

According to Oracle Java Documentation, collection is an object that represents a group of objects
Collection framework consists of collection interfaces, general purpose implementations, algorithms, etc.

Collection Interfaces are divided into 2 groups:

The first one is java.util.Collection. It consists of the following: Set, SortedSet, NavigableSet, Queue, BlockingQueue, TransferQueue, Deque, BlockingDeque.

The second one is java.util.Map. It consists of: SortedMap, NavigableMap, ConcurrentMap, ConcurrentNavigableMap. 

The collection interface is at the root of the collections framework hierarchy. 

Collections:

List interface is an ordered collection that functions as an array for its operations.

Set allows us to store elements in sets as in mathematics. Elements cant be duplicate. Sets are an unordered collection.

Queue is an ordered collection which follows the First In First Out manner to store and access elements.

Java Map : allows elements to be stored in key/value pairs. Keys are unique names that can be used to access a particular element in a map. Each key has a single value associated with it.

Java Iterator: provides methods that can be used to access the elements of collections.

Methods available in all sub-interfaces of Collection:
add(), size(), remove(), iterator(), addAll(), removeAll(), clear().

Most of these are self explanatory. Iterator method returns an iterator to access elements of the collection.

addAll() and removeAll() add and remove respectively, all the elements of the specified collection from/to the collection.

Java List Interface:

Since these are interfaces, we cant create objects from them. We need to use the classes defined in Collections framework.

The following classes are used to implement List :
ArrayList, LinkedList, Vector, Stack

Import java.util.List package to use List.
Implementation :
List<datatype> listname = new ListType<>();

example: List<String> listA = new ArrayList<>();

Apart from the common methods of collection, get(), set(), toArray(), contains() additional methods are available in List.

ArrayList

List extends Collection and ArrayList implements List. Unlike a traditional Java array, ArrayList are dynamic. They are resizable arrays which do not need to declare the size before use. 

ArrayList<type>  arrayList = new ArrayList<>();

import java.util.ArrayList;

class Main {
    
    public static void main(String[] args){
        
        ArrayList<Integer> numbers = new ArrayList<>();
        
        numbers.add(1);
        numbers.add(2);
        numbers.add(3);
        System.out.println(numbers);
        numbers.set(2,6);
        System.out.println("List after updating: " + numbers);
        numbers.add(4);
        numbers.remove(3);
        System.out.println(numbers + "\nGet Element at 2: " + numbers.get(2));
        
    }
}


For iterating through elements using foreach loop:

for(Integer number : numbers){
            System.out.println(number + ", ");
        }
    }

Additional Methods of ArrayList: sort(), clone(), contains(), ensureCapacity(), isEmpty(), indexOf();


Java Vector

One of the main differences in ArrayList and Vector is that the vector class locks on an operation. Only one thread can access it at a time, it is not asynchronous. In array lists , methods are not synchronized. Thus vectors are less efficient and array list is recommended.

To import: java.util.Vector;
Implement: Vector<Type> vector =  new Vector<>();

Methods are the same as ArrayList so we wont go much into them here. Though note that some arrayList methods dont work in vectors.

Java Stack


Stack extends Vector, Vector implements List, List extends Collection.

In the stack, elements are stored and accessed in Last In First Out manner. 

To import: java.util.Stack;
Implement: Stack<Type> st =  new Stack<>();

 Methods of stack: Stack inherits all methods of Vector class, and contains 5 additional methods which are, push(), pop(), search(), peek(), empty(). Push and pop insert at top and remove from the top of the stack. Peek returns the element at the top of the stack. Search gives the position of an element from the top of the stack. Empty checks if the stack is empty and returns boolean.

However, it is recommended to use ArrayDeque to implement stack as it is likely to be faster and better.

 (also check Queue, Priority queue, linkedlist )

Priority queue provides functionality of heap data structure.

Java ArrayDeque

Queue extends Collection, Deque extends Queue, and ArrayDeque implements Queue and Deque.

Methods: add(), addFirst(), addLast() which is same as add, offer(), offerFirst(), offerLast(), getFirst(), getLast(),peek(), peekFirst(), peekLast(), remove/removeFirst(), removeLast(), poll(), pollFirst(), pollLast(), iterator(), descendingIterator(), element(), toArray(), clone().
For implementing a stack it provides push, peek, pop

ArrayDeque is faster than LinkedList. 

Apart from these, there also exist BlockingQueue interface which is implemented by  ArrayBlockingQueue, LinkedblockingQueue. Blocking queue is considered as a thread safe collection, it can be helpful in multithreading operations.


Java Map Interface:

The map interface contains 3 different sets: set of keys, values, and key/value associations ( mapping ).

Classes that implement map:
HashMap, EnumMap, LinkedHashMap, WeakHashMap, TreeMap

SortedMap, NavigableMap, ConcurrentMap are classes that extend Map.

Implementation: Map<key, value> numbers = new HashMap<>();

Methods: Refer to official documentation at https://docs.oracle.com/javase/8/docs/api/java/util/Map.html

HashMap

import java.util.HashMap;

class Main {
    
    public static void main(String[] args){
        
        HashMap<Integer,String> map = new HashMap<Integer, String>();
        
        map.put(1,"Sam");
        map.put(2,"Bam");
        map.put(3,"Ram");
        
        System.out.println(map);
        System.out.println(map.keySet());
        System.out.println(map.values());
        System.out.println(map.get(2));
        System.out.println(map.entrySet());
        
        for(String value: map.values()){
            System.out.println(value);
        }
    }
}

Post a Comment

0 Comments