Collections in Java – with Examples For Beginners

In Java, the collections can be defined as a framework that gives architecture to store and control the group of objects. The Java collections can be used to achieve all the operations that are carried out on data including searching, insertion, sorting, deletion, and manipulation.

The Java collection refers to one unit of objects. The framework of the Java collection gives various interfaces such as set, queue, list, and deque and various classes such as array list, vector, linked list, priority queue, hash set, linked hash set, and tree set.

Collections in Java

A collection in Java is defined as one unit of objects.

Framework in Java

The framework can be defined as an optional ready-made architecture that is used to represent a group of classes and interfaces.

Collection framework

The collection framework is used to represent a unified architecture to store and control a group of objects. It includes:

  • Interfaces and classes
  • Algorithm

Hierarchy of the collection framework

The following is the hierarchy of the collection framework with the classes and interfaces included in the collection framework:

Hierarchy of the collection framework

Methods of the collection interface

The following are the methods that are declared in the collection interface:

  • public boolean add (Object element):

This method inserts an element in this collection.

  • public boolean addAll (Collection c):

This method inserts particular collection elements in the called collection.

  • public boolean remove (Object element):

This method removes an element from the collection.

  • public boolean removeAll (Collection c):

This method removes all the elements of a particular collection from the called collection.

  • public boolean retainAll (Collection c):

This method removes all the elements of the called collection except the particular collection.

  • public int size():

This method is used to find out the total number of elements in the collection and to return it.

  • public void clear():

This method is used to delete the total number of elements from the collection.

  • public boolean contains (Object element):

This method searches an element.

  • public boolean containsAll (Collection c):

This method searched the particular collection in this collection.

  • public Iterator iterator():

This method is used to find out an iterator and to return it.

  • public Object[] toArray():

This method is used to convert a collection into an array.

  • public boolean isEmpty():

This method returns true if the collection is empty otherwise returns false.

  • public boolean equals (Object element):

This method is used to match the two collections.

  • public int hashCode()

This method is used to find out the hash code number of the collection and to return it.

Iterator interface

The iterator interface allows the users to iterate the elements only in a forward direction.

Methods of the iterator interface

The following are the methods that are used in the iterator interface:

  • public boolean hasNext():

This method is used to check whether the iterator has more elements or not.

  • public Object next():

This method is used to find out the element and return it and to move the cursor pointer to the following element.

  • public void remove():

This method is used to delete the last elements that the iterator had returned. It is not used more frequently.

Java non-generic Vs. Generic collection

The Java collection framework used to be non-generic before version 1.5. Since, the JDK version 1.5, it has been made generic.

The Java new generic facilitates the users to have only a single type of object in the collection. The typecasting is not needed during the runtime because it is type safe now.

In the generic collection, the users have to specify the type in angular braces. The ArrayList is imposed to have only a single type of objects in it. The compile time error is thrown if the users try to add another type of object.

The methods to iterate the elements of the collection in the Java

The following are the two ways that can be used in order to traverse collection elements:

  • By for each loop
  • By iterator interface

Java list interface

The list interface is the child interface of the collection and is a factory of the list iterator interface. It includes various methods that are used in inserting and removing elements in the index basis.

Java list interface

The following is the declaration of this interface:

  • public interface List<E>

Methods of the Java list interface

The following are the methods that are used in the Java list interface:

  • void add (int index, Object element):

This method inserts the element into the called list at the index passed in the index.

  • boolean addAll (int index, Collection c):

This method inserts all elements of c into the called list at the index passed in the index.

  • object get (int index):

This method finds out the object that is stored at the particular index inside the called collection and returns it.

  • object set (int index, Object element):

This method assigns an element to the particular location that the index inside the called list specifies.

  • object remove (int index):

This method deletes the element at the position index from the called list and returns the removed element.

  • ListIterator listIterator():

This method finds out an iterator to the beginning of the called list and returns it.

  • ListIterator listIterator (int index):

This method finds out an iterator to the called list that starts a particular index and returns it.

Java ListIterator interface

The list iterator interface traverses the element in the forward and the backward director.

Java ListIterator interface declaration

The following is the declaration of this interface:

  • public interface ListIterator<E>

Methods of the Java ListIterator interface

The following are the methods that are used in the Java list iterator interface:

  • boolean hasNext():

This method is used to check whether the list iterator contains more elements when the list is being traversed in the forward direction or not.

  • Object next():

This method finds out the following element in the list and returns it and forwards the position of the cursor.

  • boolean hasPrevious():

This method is used to check whether the list iterator contains more elements when the list is being traversed in the backward direction or not.

  • Object previous():

This method finds out the previous element in the list and returns it and moves the position of the cursor backward.

# HashSet class

The Java hash set class generates a collection that stores using the hash table. The abstract set class is inherited by this class and the set interface is implemented by this class.

The hash set class includes only the unique elements and it uses the hashing mechanism in order to store the elements.

Dissimilarities between the list and set

The list includes duplicate elements but the set only includes the unique elements.

Hierarchy of the HashSet class

The abstract set class is extended by this class and the set interface is implemented by the abstract set class. The collection and iterable interfaces are inherited by the set class.

HashSet class declaration

The following is the declaration of this class:

  • public class HashSet<E> extends abstract set implements collection

Constructors of the Java HashSet class

The following are the constructors that are used in the Java hash set class:

  • HashSet():

This constructor creates a default hash set.

  • HashSet (int capacity):

This constructor initializes the capacity of the hash set to the integer value capacity provided. As the elements get added to the hash set, the capacity automatically increases.

  • HashSet (int capacity, float loadFactor):

This constructor initializes the capacity of the hash set to the integer value capacity provided and the particular load factor.

  • HashSet (Collection c):

This constructor uses the elements of the collection c in order to initialize the hash set.

Methods of the Java HashSet class

The following are the methods that are used in the Java hash set class:

  • Boolean add (Object o):

This method adds a particular element to the set it is not already there.

  • void clear():

This method deleted all of the elements from this set.

  • object clone():

This method finds out a shallow copy of the hash set instance and returns it. In this method, the elements are not cloned themselves.

  • boolean contains (Object o):

This method checks whether the set includes a particular element or not.

  • boolean isEmpty():

This method checks whether the set includes zero elements or not.

  • Iterator<E> iterator():

This method finds out an iterator over the elements in the set and returns it.

  • boolean remove (Object o):

This method deletes the particular element from the set if it is there.

  • int size():

This method finds out the number of elements in the set and returns it.

  • Spliterator<E> spliterator():

This method constructs a late binding and a fail fast spliterator over the elements in the set.

Java LinkedHashSet class

The Java linked hash set class is a hash table and a linked list implementation of the set interface. The hash set class is inherited by this class and the set interface is implemented by this class.

Like the hash set class, this class only includes unique elements. This class manages the insertion order and gives all of the optional set operations and permits the zero elements.

Hierarchy of the Java LinkedHashSet class

The hash set class is extended by this class and the set interface is implemented by the hash set class. The collection and iterable interfaces are inherited by the set interface.

Java LinkedHashSet class declaration

The following is the declaration of this class:

  • public class LinkedHashSet<E> extends hash set implements set

Constructors of the Java LinkedHashSet class

The following are the constructors that are used in the Java linked hash set class:

  • HashSet():

This constructor created a default hash set.

  • HashSet (Collection c):

This constructor used the elements of the collection c in order to initialize the hash set.

  • LinkedHashSet (int capacity):

This constructor initializes the capacity of the linked hash set to the integer value capacity provided.

  • LinkedHashSet (int capacity, float fillRatio):

This constructor initializes the capacity as well as the fill ratio of the hash set from its arg.

# Java TreeSet class

The Java tree set class implements the set interface that used a tree for storing the objects in an ascending order. The abstract set class is inherited by this class and the navigable set interface is implemented by this class.

Like the hash set class, this class only includes the unique elements. It manages an ascending order and the times for accessing and retrieving are very fast.

Hierarchy of the TreeSet class

The navigable set interface is implemented by this class and the sorted set, set, collection, and iterable interfaces are extended by the navigable set interface.

Java TreeSet class declaration

The following is the declaration of the Java tree set class:

  • public class TreeSet<E> extends abstract set implements navigable set

Constructors of the Java TreeSet class

The following are the constructors that are used in the Java tree set class:

  • TreeSet():

This constructor creates an empty tree set that will be sorted in an ascending order on the basis of the natural order of the tree set.

  • TreeSet (Collection c):

This constructor creates a new tree set that includes the elements of the collection c.

  • TreeSet (Comparator comp):

This constructor creates an empty tree set that will be sorted on the basis of the comparator provided.

  • TreeSet (SortedSet ss):

This constructor creates a tree set that includes the elements of the sorted set provided.

Methods of the Java TreeSet class

The following are the methods that are used in the Java tree set class:

  • boolean addAll (Collection c):

This method adds all of the elements in the particular collection to the set.

  • boolean contains (Object o):

This method checks whether the set includes the particular element or not.

  • boolean isEmpty():

This method checks whether the set includes zero elements or not.

  • boolean remove (Object o):

This method deletes the particular element from the set if it is there.

  • void add (Object o):

This method adds a particular element to the set if it does not already exist.

  • void clear():

This method deletes all of the elements from the set.

  • Object clone():

This method finds out a shallow copy of the tree set instance and returns it.

  • Object first():

This method finds out the first element of the present sorted set and returns it.

  • Object last():

This method finds out the last element of the present sorted set and returns it.

  • int size():

This method finds out the number of elements in the set and returns it.

Java Queue Interface

The Java queue interface places the elements in the first in first out manner in which the first element is deleted first and the last element is deleted at last.

Java Queue Interface declaration

The following is the declaration of this interface:

  • public interface Queue<E>

Methods of the Java queue interface

The following are the methods that are used in the Java queue interface:

  • boolean add (object):

This method inserts the particular element into the queue and returns true after the element has been successfully inserted.

  • boolean offer (object):

This method inserts the particular element into the queue.

  • Object remove():

This method is used for retrieving and removing the head of this queue.

  • Object poll():

This method is used for retrieving and removing the head of this queue and this method returns null in the case in which the queue is empty.

  • Object element():

This method is used only for retrieving the head of this queue, not for removing.

  • Object peek():

This method is used only for retrieving the head of this queue, not for removing. It returns null in the case in which the queue is empty.

Java PriorityQueue class

The priority queue class allows the users to use the queue. However, this class does not place the elements in the first in first out manner. The abstract queue class is inherited by this class.

Java PriorityQueue class declaration

The following is the declaration of this class:

  • public class PriorityQueue<E> extends abstract queue

Java Deque interface

The Java deque interface is a linear collection that aids in inserting and removing the element at both ends. The full form of the deque is double ended queue.

Java Deque interface declaration

The following is the declaration of this interface:

  • public interface Deque<E>

Methods of the Java deque interface

The following are the methods that are used in the Java deque interface:

  • boolean add (object):

This method inserts the particular element into the deque and returns true after the element has been successfully inserted.

  • boolean offer (object):

This method inserts the particular element into the deque.

  • Object remove():

This method is used for retrieving and removing the head of this deque.

  • Object poll():

This method is used for retrieving and removing the head of this deque and this method returns null in the case in which the deque is empty.

  • Object element():

This method is used only for retrieving the head of this deque, not for removing.

  • Object peek():

This method is used only for retrieving the head of this deque, not for removing. It returns null in the case in which the deque is empty.

ArrayDeque class

The array deque class allows the users to use the deque and the resizable array. The abstract collection class is inherited by this class and the deque interface is implemented by this class.

The users can add or delete elements from both sides in this class, unlike the queue class but the zero elements are not allowed in the array deque class. This class has no capacity limitation and is faster than the linked list and the stack. However, this class is not threaded safe in the case in which the external synchronization is absent.

ArrayDeque class declaration

The following is the declaration of this class:

  • public class ArrayDeque<E> extends abstract collection implements deque

Java map interface

The map interface includes values depending on the key that is a key and a value pair. Each key and value pair is called entry and this interface includes unique keys only.

The man interface is very useful during the searching, updating, and deletion of the elements depending on a key.

Java map hierarchy

The map and the sorted map interfaces are the two interfaces that implement the map in the Java and the hash map, linked hash map, and the tree, map are the three classes.

The duplicate keys are not allowed by the map but the users can have duplicate values. The hash map and the linked hash map classes allow the zero keys and values bit the tree, map class does not allow any zero key or value.

The keyset() or the entrySet() method must be used to convert a map into a set because it cannot be traversed.

  • Hash map:

This is the implementation of the map that does not manage any order.

  • Linked hash map:

This is the implementation of the map that manages an insertion order and inherits the hash map class.

  • Tree map:

This is the implementation of the map and the sorted map that manages an ascending order.

Methods of the map interface

The following are the methods that are used in the map interface:

  • Object put (Object key and value):

This method inserts an entry in the map.

  • void putAll (Map map):

This method inserts the particular map in this map.

  • Object remove (Object key):

This method removes an entry for a particular key.

  • Object get (Object key):

This method finds out the value of a particular key and returns it.

  • boolean containsKey (Object key):

This method searches a particular key from this map.

  • Set keySet():

This method finds out the set view that has all the keys and returns it.

  • Set entrySet():

This method finds out the set view that has all the keys and values and returns it.

Map entry Interface

The entry is a child interface of the map interface and it is available in the Map.Entry name. This interface includes the methods to find out the key and the value.

Methods of the map entry interface

The following are the methods that are used in the map entry interface:

  • Object getKey():

This method finds out the key and returns it.

  • Object getValue():

This method finds out the value and returns it.

Java HashMap class

The Java hash map class includes the values that are based on the key and the map interface is implemented by this class by using a hash table. The abstract map class is inherited by this method and this method only includes the unique elements. This class may have a single zero key and many zero values and this class does not maintain any order.

 

Hierarchy of the hash map class

The abstract map class is extended by this class and the map interface is implemented by this class.

Java HashMap class declaration

The following is the declaration of this class:

  • public class HashMap<K, V> extends abstract map implements map

Java HashMap class parameters

The following are the parameter of the Java hash map class:

  • K:

This parameter is the kind of the key that this map maintains.

  • V:

This parameter is the kind of the values that are mapped.

Constructors of the Java HashMap class

The following are the constructors that are used in the Java hash map class:

  • HashMap():

This constructor creates a default hash map.

  • HashMap (Map m):

This constructor is used in the initialization of the hash map by using the elements of the map object m provided.

  • HashMap (int capacity):

This constructor is used in the initialization of the capacity of the hash map to the int value capacity provided.

  • HashMap (int capacity, float fillRatio):

This constructor is used in the initialization of both the capacity and the fill ratio of the hap map by using its arg.

Methods of Java HashMap class

The following are the methods that are used in the Java hash map class:

  • void clear():

This method deletes all of the mappings from this map.

  • boolean containsKey (Object key):

This method is used to check whether the map includes a mapping of a particular key or not.

  • boolean containsValue (Object value):

This method is used to check whether the map maps single or multiple keys to a particular value or not.

  • boolean isEmpty():

This method is used to check whether the map includes no key-value mappings or not.

  • Object clone():

This method finds out a shallow copy of this hash map instance and returns it. However, in this method, the keys and the values are not cloned.

  • Set entrySet():

This method finds out a set view of the mappings included in this map and returns it.

  • Set keySet():

This method finds out a set view of the keys included in this map and returns it.

  • Object put (Object key and value):

This method relates a particular value with a particular key in this map.

  • int size():

This method finds out the number of key-value mappings in this map and returns it.

  • collection values():

This method finds out a collection view of the values included in this map and returns it.

1 thought on “Collections in Java – with Examples For Beginners

Leave a Reply

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