Collections in Java

Back to home
Logicmojo - Updated Jan 11, 2023



Introduction to Collection

If we want to represent a group of "individual items" as a single entity, we should use collection. The foundation interface of the entire collection structure can be thought of as Collection. The most common methods that may be applied to any collection object are defined by the collection interface.

In JDK 1.2, a new framework called "Collection Framework" was established, which contains all of the collection classes and interfaces. The two basic "root" interfaces of Java collection classes are the Collection interface (java.util.Collection) and the Map interface (java.util.Map).

9(Nine) key interfaces of collection framework:

  1. 1. Collection

  2. 2. List

  3. 3. Set

  4. 4. SortedSet

  5. 5. NavigableSet

  6. 6. Queue

  7. 7. Map

  8. 8. SortedMap

  9. 9. NavigableMap

Methods of Collection interface

The Collection interface declares a large number of methods. The following are the details:

No.MethodDescription
1public boolean add(E e)It's used to add a new item to this collection.
2public boolean addAll(Collection<? extends E> c)It's used to populate the calling collection with the provided collection elements.
3public boolean remove(Object element)It's utilised to get rid of an item from a collection.
4public boolean removeAll(Collection<?> c)It is used to remove all elements from the calling collection that belong to the specified collection.
5default boolean removeIf(Predicate<? super E> filter)It's used to get rid of all the elements in the collection that match the predicate.
6public boolean retainAll(Collection<?> c)It's used to remove all of the elements from the calling collection except the one supplied.
7public int size()It returns the collection's total number of elements.
8public void clear()It removes the collection's entire amount of components.
9public boolean contains(Object element)It's used to find a specific element.
10public boolean containsAll(Collection<?> c)It's used to look for a certain collection within a collection.
11public Iterator iterator()It gives you an iterator as a result.
12public Object[] toArray()It turns a collection into an array.
13public <T> T[] toArray(T[] a)It turns a collection into an array. The returned array has the same runtime type as the provided array.
14public boolean isEmpty()It looks to see if the collection is empty.
15default Stream<E> parallelStream()It returns a possibly parallel Stream whose source is the collection.
16default Stream<E> stream()It returns a sequential Stream whose source is the collection.
17default Spliterator<E> spliterator()It creates a Spliterator from the collection's provided elements.
18public boolean equals(Object element)It corresponds to two different collections.
19public int hashCode()It returns the collection's hash code number.

1. List

It is the Collection's child interface. We should use the List interface if we want to represent a set of unique objects as a single entity where "duplicates are allowed and insertion order must be preserved."

This interface is for list data, which allows us to store all of the objects in a sorted collection. This also allows for duplicated data to exist. This list interface is implemented by a number of classes, including ArrayList, Vector, Stack, and others. Because they all implement the list, we can make a list object with any of these classes.

The List interface is implemented by the following classes:

A. ArrayList

ArrayList provides us with dynamic arrays in Java. Despite the fact that it is slower than regular arrays, it may be beneficial in programmes that demand a lot of array manipulation. When the size of a collection grows, the size of an ArrayList grows as well, and when the size of a collection diminishes, the size of an ArrayList shrinks as well. We can access the list at random using the Java ArrayList. ArrayList does not support primitive types like int, char, and so on. In such cases, a wrapper class will be required. Let's look at an example to better grasp the ArrayList:

Example in Java

import java.util.*;
class ArrayListDemo 
{
	public static void main(String[] args) 
	{
		ArrayList a=new ArrayList();
		a.add("A");
		a.add(10);
		a.add("A");
		a.add(null);
		System.out.println(a);//[A, 10, A, null]
		a.remove(2);
		System.out.println(a);//[A, 10, null]
		a.add(2,"m");
		a.add("n");
		System.out.println(a);//[A, 10, m, null, n]
		}
}


B. LinkedList

The LinkedList data structure is a linear data structure in which items are not kept in sequential order and each element is a distinct object with a data component and an address piece. Connecting the elements is done through pointers and addresses. A node is a term used to describe any element.

Example in Java

import java.util.*;
class LinkedListDemo 
{
	public static void main(String[] args) 
	{
		LinkedList l=new LinkedList();
		l.add("bhaskar");
		l.add(30);
		l.add(null);
		l.add("bhaskar");
		System.out.println(l);//[bhaskar, 30, null, bhaskar]
		l.set(0,"software");
		System.out.println(l);//[software, 30, null, bhaskar]
		l.set(0,"venky");
		System.out.println(l);//[venky, 30, null, bhaskar]
		l.removeLast();
		System.out.println(l);//[venky, 30, null]
		l.addFirst("vvv");
		System.out.println(l);//[vvv, venky, 30, null]
	}
}


C. Vector

A vector in Java provides us with dynamic arrays. Despite the fact that it is slower than regular arrays, it may be beneficial in programmes that demand a lot of array manipulation. This is comparable to ArrayList in terms of implementation. A vector is synchronised, although an ArrayList is not. Let's have a look at an example to help you understand the Vector:

Example in Java

import java.util.*;
class VectorDemo 
{
	public static void main(String[] args) 
	{
		Vector v=new Vector();
		System.out.println(v.capacity());//10
		for(int i=1;i<=10;i++)
		{
			v.addElement(i);
		}
		System.out.println(v.capacity());//10
	 	v.addElement("A");
		System.out.println(v.capacity());//20
		System.out.println(v);//[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, A]
	}
}


C. Stack

The Stack class models and implements the Stack data structure. The class is structured according to the last-in-first-out principle. In addition to the basic push and pop operations, the class offers three extra functions: empty, search, and peek. This class can also be referred to as a subclass of Vector. Let's look at an example to better grasp the stack:

Example in Java

import java.util.*;
class StackDemo 
{
	public static void main(String[] args) 
	{
		Stack s=new Stack();
		s.push("A");
		s.push("B");
		s.push("C");
		System.out.println(s);//[A, B, C]
		System.out.println(s.pop());//C
		System.out.println(s);//[A, B]
		System.out.println(s.peek());//B
		System.out.println(s.search("A"));//2
		System.out.println(s.search("Z"));//-1
		System.out.println(s.empty());//false
	}
}


2. Set

A set is an unsorted group of things that can't have the same value twice. When we wish to avoid duplication of items and just maintain the ones that are unique, we use this collection. This set interface is implemented by a number of classes, including HashSet, TreeSet, LinkedHashSet, and others. Because they all implement the set, we can make a set object using any of these classes.

The Set interface is implemented by the following classes:

A. HashSet

By default, the HashSet class implements the hash table data structure. The HashSet makes no guarantees about the order in which the objects are placed. The objects' hashcodes are used to insert them. This class can also be used to insert NULL elements. Let's look at an example to better grasp HashSet:

Example in Java

import java.util.*;
class HashSetDemo 
{
	public static void main(String[] args) 
	{
		HashSet h=new HashSet();
		h.add("B");
		h.add("C");
		h.add("D");
		h.add("Z");
		h.add(null);
		h.add(10);
		System.out.println(h.add("Z"));//false
		System.out.println(h);//[null, D, B, C, 10, Z]
	}
}


B. LinkedHashSet

A HashSet is quite similar to a LinkedHashSet. The difference is that the data is saved in a doubly linked list, which keeps the entries in their original order. Consider the following LinkedHashSet example:

Example in Java

import java.util.*;
class LinkedHashSetDemo 
{
	public static void main(String[] args) 
	{
		LinkedHashSet h=new LinkedHashSet();
		h.add("B");
		h.add("C");
		h.add("D");
		h.add("Z");
		h.add(null);
		h.add(10);
		System.out.println(h.add("Z"));//false
		System.out.println(h);//[B, C, D, Z, null, 10]
	}
}


3. SortedSet

This interface resembles the set interface in appearance. The only difference is that this interface has more ways for keeping element order. The sorted set interface is a variant of the set interface for managing sorted data. This interface is implemented by the TreeSet class. Because this class implements the SortedSet interface, we can use it to generate a SortedSet object.

The sorted set interface is implemented by the TreeSet class.

A. TreeSet

The TreeSet class is used to store data in a Tree. Whether or not an explicit comparator is provided, a set keeps the order of the components by using their natural ordering. If the Set interface is to be effectively implemented, it must be compatible with equals. Depending on which constructor is chosen, it can also be ordered by a Comparator provided at a specified build time. Consider the following scenario to better understand TreeSet:

Example in Java

import java.util.*;
class TreeSetDemo 
{
	public static void main(String[] args) 
	{
		TreeSet t=new TreeSet();
		t.add("A");
		t.add("a");
		t.add("B");
		t.add("Z");
		t.add("L");
		//t.add(new Integer(10));//ClassCastException
		//t.add(null);//NullPointerException
		System.out.println(t);//[A, B, L, Z, a]
	}
}


4. Queue

The FIFO (First In First Out) order of a real-world queue line is followed by a queue interface. This interface is used to store all elements where the order of the elements matters. When we try to purchase a ticket, for example, the tickets are sold on a first-come, first-serve basis. As a result, the ticket is given to the person whose request is first in line. There are classes like PriorityQueue, ArrayDeque, and others. We can use any of these subclasses to generate a queue object because they all implement the queue. As an illustration,

The PriorityQueue implementation of the queue interface is the most often used.

A. Priority Queue

A PriorityQueue is used when the objects must be processed in order of priority. Although it is common knowledge that a queue follows the First-In-First-Out technique, there are times when the contents of the queue must be handled in order of priority, and this class is used in these cases. The PriorityQueue's base is a priority heap. The members of the priority queue are ordered according to natural ordering or by a Comparator provided at queue formation time, depending on whether the constructor is utilised. Consider the following example of a priority queue:

Example in Java

import java.util.*;
class PriorityQueueDemo
{
	public static void main(String[] args) 
	{
		PriorityQueue q=new PriorityQueue();
		//System.out.println(q.peek());//null
		//System.out.println(q.element());//NoSuchElementException
		for(int i=0;i<=10;i++)
		{
			q.offer(i);
		}
		System.out.println(q);//[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
		System.out.println(q.poll());//0
		System.out.println(q);//[1, 3, 2, 7, 4, 5, 6, 10, 8, 9]
	}
}


5. Map

A map is a data structure that allows key-value pairs to be created from data. This interface does not support duplicate keys because the same key cannot have multiple mappings. A map is useful when there is data and we want to do actions based on the key. This map interface is implemented by a number of classes, including HashMap and TreeMap. Because they all implement the map, we can make a map object using any of these types.

The most popular implementation of the Map interface is a HashMap.

A. HashMap

The HashMap implementation of Java's Map interface is the most basic. (Key, Value) pairs are used to store the information. In order to access a HashMap value, we need to know its key. HashMap employs the method of hashing. Hashing is a technique for compressing a large String into a smaller String that represents the same String in order to speed up indexing and search. HashSet makes use of HashMap internally. To better understand HashMap, consider the following example:

import java.util.*;
class HashMapDemo 
{
	public static void main(String[] args) 
	{
		HashMap m=new HashMap();
		m.put("chiranjeevi",700);
		m.put("balaiah",800);
		m.put("venkatesh",200);
		m.put("nagarjuna",500);
		System.out.println(m);//{nagarjuna=500, venkatesh=200, balaiah=800, chiranjeevi=700}
		System.out.println(m.put("chiranjeevi",100));//700
		Set s=m.keySet();
		System.out.println(s);//[nagarjuna, venkatesh, balaiah, chiranjeevi]
		Collection c=m.values();
		System.out.println(c);//[500, 200, 800, 100]
		Set s1=m.entrySet();
		System.out.println(s1);//[nagarjuna=500, venkatesh=200, balaiah=800, chiranjeevi=100]
		Iterator itr=s1.iterator();
		while(itr.hasNext())
		{
			Map.Entry m1=(Map.Entry)itr.next();
			System.out.println(m1.getKey()+"......"+m1.getValue());//nagarjuna......500						 				      //venkatesh......200							 			      //balaiah......800								  			      //chiranjeevi......100
			if(m1.getKey().equals("nagarjuna"))
			{
				m1.setValue(1000);
			}
		}
		System.out.println(m);//{nagarjuna=1000, venkatesh=200, balaiah=800, chiranjeevi=100}
	}
}


With this article at Logicmojo, you must have the complete idea of Collections in java.