Java Collections Framework - Collections in Java With Examples

Swatee Chand
Edureka
Published in
9 min readMay 13, 2017
Java Collections - Edureka

In my previous articles, you have learned about OOP concepts and Java Strings. Now, let us move towards the slightly advance concept, i.e Java collections. Java collections refer to a single unit of objects. You can perform all operations on data such as searching, sorting, insertion, manipulation, deletion, etc. by Java collections.

Now, let us move ahead in this blog, where we will understand each aspect of it in the following sequence:

  1. What is a Java collection framework?
  2. Java collection framework Hierarchy
  3. Interface
  4. List
  5. Queue
  6. Sets

Let’s get started with the first topic in the Java collections blog.

What is a Java Collection Framework?

A Java collection framework provides an architecture to store and manipulate a group of objects. A Java collection framework includes the following:

  • Interfaces
  • Classes
  • Algorithm

Let’s learn about them in detail:

Interfaces:

Interface in Java refers to the abstract data types. They allow Java collections to be manipulated independently from the details of their representation. Also, they form a hierarchy in object-oriented programming languages.

Classes:

Classes in Java are the implementation of the collection interface. It basically refers to the data structures that are used again and again.

Algorithm:

Algorithm refers to the methods which are used to perform operations such as searching and sorting, on objects that implement collection interfaces. Algorithms are polymorphic in nature as the same method can be used to take many forms or you can say perform different implementations of the Java collection interface.

The Java collection framework provides the developers to access prepackaged data structures as well as algorithms to manipulate data. Next, let us move to the Java collections framework hierarchy and see where these interfaces and classes reside.

Java Collection Framework Hierarchy

As we have learned Java collection framework includes interfaces and classes. Now, let us see the Java collections framework hierarchy.

Java Collection Framework Hierarchy - Java Collections

In the above image, the blue part refers to the different interfaces and the yellow part defines the class. Now, let us understand these components in detail.

Interface

Iterator interface :

An iterator is an interface that iterates the elements. It is used to traverse the list and modify the elements. Iterator interface has three methods which are mentioned below:

  1. public boolean hasNext() — This method returns true if the iterator has more elements.
  2. public object next() — It returns the element and moves the cursor pointer to the next element.
  3. public void remove() — This method removes the last elements returned by the iterator.

There are three components that extend the collection interface i.e List, Queue and Sets. Let’s learn about them in detail:

List

A List is an ordered Collection of elements which may contain duplicates. It is an interface that extends the Collection interface. Lists are further classified into the following:

  1. ArrayList
  2. LinkedList
  3. Vectors

Let’s go into detail on each one of them:

Array list:

ArrayList is the implementation of List Interface where the elements can be dynamically added or removed from the list. Also, the size of the list is increased dynamically if the elements are added more than the initial size.

Array List - Java Collections

Syntax:

ArrayList object = new ArrayList ();

Some of the methods in array list are listed below:

Methods in ArrayList — Java Collections

Let us understand Array list with a programmatic example:

import java.util.*;
class ArrayListExample{
public static void main(String args[]){

ArrayList al=new ArrayList(); // creating array list
al.add("Jack"); // adding elements
al.add("Tyler");
Iterator itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}

In the above code, it will return the names that we have added using add() method i.e:

Jack 
Tyler

Linked List:

Linked List is a sequence of links which contains items. Each link contains a connection to another link.

Syntax: Linkedlist object = new Linkedlist();

Java Linked List class uses two types of Linked list to store the elements:

  • Singly Linked List
  • Doubly Linked List

Singly Linked List:

In a singly Linked list, each node in this list stores the data of the node and a pointer or reference to the next node in the list. Refer to the below image to get a better understanding of single Linked list.

Single Linked List - Java Collections

Doubly Linked List:

In a doubly Linked list, it has two references, one to the next node and another to the previous node. You can refer to the below image to get a better understanding of doubly linked list.

Doubly Linked List - Java Collections

Some of the methods in the linked list are listed below:

Methods in Linked List — Java Collections

Let us understand linked list with a programmatic example:

import java.util.*;
public class LinkedlistExample{
public static void main(String args[]){
LinkedList <String> al=new LinkedList <String>(); // creating linked list
al.add("Rachit"); // adding elements
al.add("Rahul");
al.add("Rajat");
Iterator <String> itr = al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}

The output of the above program would be:

Rachit 
Rahul
Rajat

Vectors :

Vectors are similar to arrays, where the elements of the vector object can be accessed via an index into the vector. Vector implements a dynamic array. Also, the vector is not limited to a specific size, it can shrink or grow automatically whenever required. It is similar to ArrayList, but with two differences :

  • Vector is synchronized.
  • Vector contains many legacy methods that are not part of the collections framework.
Vectors - Java Collections

Syntax:

Vector object = new Vector(size,increment);

Below are some of the methods of the Vector class:

Methods in Vector Class - Java Collections

Now, let us move to the next subtype of the Java Collections interface i.e Queue.

Queue

Queue in Java follows a FIFO approach i.e. it orders the elements in First In First Out manner. In a queue, the first element is removed first and last element is removed in the end. Each basic method exists in two forms: one throws an exception if the operation fails, the other returns a special value.

Queue - Java Collections

Also, priority queue implements Queue interface. The elements of the priority queue are ordered according to their natural ordering, or by a Comparator provided at the queue construction time. The head of this queue is the least element with respect to the specified ordering.

Below are some of the methods of Java Queue interface:

Methods in Queue Interface - Java Collections

Let us understand these priority queues with a programmatic example:

import java.util.*;
class QueueExample {
public static void main(String args[]){
// creating priority queue
PriorityQueue <String> queue=new PriorityQueue <String>();
queue.add("Amit"); // adding elements
queue.add("Rachit");
queue.add("Rahul");
System.out.println("head:"+queue.element());
System.out.println("head:"+queue.peek());
System.out.println("iterating the queue elements:");
Iterator itr=queue.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
queue.remove();
queue.poll();
System.out.println("after removing two elements:");
Iterator <String> itr2=queue.iterator();
while(itr2.hasNext()){
System.out.println(itr2.next());
}
}
}

In the above code, the output would be :

head:Amit
head:Amit
iterating the queue elements:
Amit
Rachit
Rahul
after removing two elements:
Rahul

Next, let us move forward to our next topic, i.e. Sets.

Sets

A Set refers to a collection that cannot contain duplicate elements. It is mainly used to model the mathematical set abstraction. Set has its implementation in various classes such as HashSet, TreeSet and LinkedHashSet.

Let’s go into detail on each one of them:

Types of Sets - Java Collections

HashSet:

Java HashSet class creates a collection that uses a hash table for storage. HashSet only contains unique elements and it inherits the AbstractSet class and implements Set interface. Also, it uses a mechanism hashing to store the elements.
Below are some of the methods of Java HashSet class:

Methods in HashSets - Java Collections

Let us understand these HashSet with a programmatic example:

import java.util.*;
class HashsetExample{
public static void main(String args[]){

HashSet <String> al=new HashSet(); // creating hashSet
al.add("Rachit"); // adding elements
al.add("Amit");
al.add("jack");
Iterator <String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}

The output of the above code would be:

Amit
Rachit
jack

Linked HashSet :

Java LinkedHashSet class is a Hashtable and Linked list implementation of the set interface. It contains only unique elements like HashSet. Linked HashSet also provides all optional set operations and maintains insertion order. Let us understand these linked HashSet with a programmatic example:

import java.util.*;
class LinkedHashsetExample{
public static void main(String args[]){
LinkedHashSet <String> al=new LinkedHashSet(); // creating linkedhashset
al.add(“Mariana”); // adding elements
al.add(“Rick”);
al.add(“Sam”);
Iterator <String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
}

The output of the above code would be:

Mariana
Rick
Sam

TreeSet :

TreeSet class implements the Set interface that uses a tree for storage. The objects of this class are stored in the ascending order. Also, it inherits AbstractSet class and implements the NavigableSet interface. It contains only unique elements like HashSet. In TreeSet class, access and retrieval time are faster.
Below are some of the methods of Java TreeSet class:

Methods in TreeSet - Java Collections

Let us understand these TreeSet with a programmatic example:

import java.util.*;
class TreeSetExample{
public static void main(String args[]){
TreeSet <String> al=new TreeSet<String>(); // creating treeSet
al.add("John"); // adding elements
al.add("Sam");
al.add("Rick");
Iterator <String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}

The output of the above program would be:

John 
Rick
Sam

Now you must be wondering what is the difference between all these sets?

HashSet stores elements in random order whereas LinkedHashSet stores elements according to insertion order and TreeHashSet stores according to natural ordering.

This is the end of the “Java Collections” article. I hope you guys are clear with Java collections framework, it’s hierarchy, interface, list, queue and sets that I have discussed above.

If you wish to check out more articles on the market’s most trending technologies like Artificial Intelligence, DevOps, Ethical Hacking, then you can refer to Edureka’s official site.

Do look out for other articles in this series which will explain the various other aspects of Java.

1. Object Oriented Programming

2. Inheritance in Java

3. Polymorphism in Java

4. Abstraction in Java

5. Java String

6. Java Array

7. Java Tutorial

8. Java Threads

9. Introduction to Java Servlets

10. Servlet and JSP Tutorial

11. Exception Handling in Java

12. Advanced Java Tutorial

13. Java Interview Questions

14. Java Programs

15. Kotlin vs Java

16. Dependency Injection Using Spring Boot

17. Comparable in Java

18. Top 10 Java frameworks

19. Java Reflection API

20. Top 30 Patterns in Java

21. Core Java Cheat Sheet

22. Socket Programming In Java

23. Java OOP Cheat Sheet

24. Annotations in Java

25. Library Management System Project in Java

26. Trees in Java

27. Machine Learning in Java

28. Top Data Structures & Algorithms in Java

29. Java Developer Skills

30. Top 55 Servlet Interview Questions

31. Top Java Projects

32. Java Strings Cheat Sheet

33. Nested Class in Java

34. Java Collections Interview Questions and Answers

35. How to Handle Deadlock in Java?

36. Top 50 Java Collections Interview Questions You Need to Know

37. What is the concept of String Pool in Java?

38. What is the difference between C, C++, and Java?

39. Palindrome in Java- How to check a number or string?

40. Top MVC Interview Questions and Answers You Need to Know

41. Top 10 Applications of Java Programming Language

42. Deadlock in Java

43. Square and Square Root in Java

44. Typecasting in Java

45. Operators in Java and its Types

46. Destructor in Java

47. Binary Search in Java

48. MVC Architecture in Java

49. Hibernate Interview Questions And Answers

Originally published at www.edureka.co on May 13, 2017.

--

--