Collections in Java Programming

Hello and welcome back, everyone. In this module, I will be talking about Collections in Java Programming. After reading this module you will get to know what Collections in Java are. Now, let’s proceed to discuss Collections in Java.

Collections in Java

Collections in Java Programming

The Collection in Java is a framework that provides a set of interfaces and classes to store and manipulate data efficiently.

A Collection is defined as a single unit of objects and a framework is a ready-made architecture that provides a set of interfaces and classes.

With the use of Collections, you can write your code quickly and efficiently. You can easily store and manipulate the data by performing operations such as searching, sorting, insertion, deletion, and traversing.

What are the advantages of the Collections framework?

The advantages of using collections are listed below:

  • By using the collections framework, you can store both homogenous and heterogeneous data.
  • It also provides flexibility since its size can be expanded according to the user’s requirements.
  • You can perform many operations such as insertion, deletion, searching, sorting, etc. very easily by the use of methods.

How is the Collection framework available in Java?

The package java.util.Collection or java.util contains all the interfaces and their implementation known as classes and algorithms for the Collection framework. Thus, you need to import the java.util.Collection package to use Collection classes and interfaces in Java.

Interfaces in Java

These are abstract data types that are used to represent collections. It consists of the method declarations.

Implementation (Classes) in Java

These are the implementation of the collection interface. They implement the methods of the interfaces.

Algorithms in Java

These are the methods for performing actions on objects that implement the collection interface, such as searching and sorting.

The different Interfaces and their implementations (Classes) in the Collection framework?

Given below is the list of interfaces in the Collection framework:

Collection Interface in Java

  • It is at the top level of the Collection framework hierarchy.
  • It is implemented by all of the collection framework’s classes.
  • It consists of a declaration of the methods available to all the classes that implement the collection interface.
  • There are many methods of Collection interface. Listed below are some of the methods of collection interfaces method:
      • boolean add(Object obj)
      • boolean addAll(Collection c)
      • boolean remove(Object obj)
      • boolean removeAll(Collection c)
      • int size()
      • void clear()

List interface in Java

  • This interface is used to store an ordered collection of elements.
  • It can have duplicate values.
  • Insertion order is preserved which means that the elements are processed or traversed in the same order that they were added to the list.
  • For example, if elements are added in the following order: 4, 2, 1, 0, 5, the traversal order is 4, 2, 1, 0, 5.
  • It is implemented by the following classes: Array List, Linked List, Vector, and Stack.

Let’s see the classes that implement the List interface.

ArrayList in Java

It is a dynamic array which means that its size can be decreased or increased as per requirement. Thus, it provides flexibility. You can randomly access the elements of the array list by using its index number.

Syntax

ArrayList <dataType> arraylistName=new ArrayList<>();

import java.util.*;
public class AraryListExample {
    public static void main(String []array){
    ArrayList<String> list=new ArrayList<>();

    // adding elements in an arraylist
    list.add("Rahul");
    list.add("Aman");
    list.add("Neha");
    list.add("Simran");
    list.add("Raman");

    // printing elements of arraylist
    System.out.println(list);
    // accessing element of arraylist by its index number
    System.out.println(list.get(0));

    // removing element
    list.remove("Aman");
    System.out.println(list);
    System.out.println("Length of arraylist ="+list.size());

    // removing element by the index number of element.
    list.remove(0);
    System.out.println(list);

    // returns false because the element doesn't exist in arraylist.
    System.out.println(list.remove("Ankit"));

    // removing all the elements of arraylist.
    list.clear();
  }
}
// Output
// [Rahul, Aman, Neha, Simran, Raman]
// Length of arraylist=5
// [Rahul, Neha, Simran, Raman]
// [Neha, Simran, Raman]
// False

Linked List in Java

It uses a linked-list data structure to store information. It can also store duplicate elements.

Syntax

LinkedList<dataType> listName=new LinkedList<>();

import java.util.*;
public class LinkedListExample {
    public static void main(String []array){
    LinkedList<Integer> list=new LinkedList<>();

    // adding elements in an arraylist
    list.add(5);
    list.add(-1);
    list.add(-6);
    list.add(0);
    list.add(13);

    // printing linked list
    System.out.println(list);

    // removing element by its index number.
    list.remove(2);
    System.out.println(list);
  }
}
// Output
// [5, -1, -6, 0, 13]
// [5, -1, 0, 13]

Vector in Java

It is similar to ArrayList, which stores elements in a dynamic array. The two key differences between ArrayList and Vector are that Vector is synchronized and has many, methods that aren’t included in the Collections framework.

Syntax
Vector <dataType> vectorName=new Vector<>();

import java.util.*;
public class VectorExample {
    public static void main(String []array){
    Vector<Float> vector=new Vector<>();

    // adding elements using add method in an arraylist
    vector.add(5.4f);
    vector.add(-4.5f);
    vector.add(9.55f);
    // adding elements using addElement method in an arraylist
    vector.addElement(6.5f);
    vector.addElement(15.76f);

    // printing vector
    System.out.println(vector);

    vector.remove(5.4f);
    System.out.println(vector);
  }
}

//Output
// [5.4, -4.5, 9.55, 6.5, 15.76]
// [-4.5, 9.55, 6.5, 15.76]

Stack in Java

It implements the stack data structure which is based on the last-in-first-out (LIFO) concept. It is a subclass of vectors.

Syntax
Stack <dataType> stackName=new Stack<>();

import java.util.*;
public class StackExample {
    public static void main(String []array){
    Stack<String> stack = new Stack<>();

    // adding elements in stack
    stack.push("Java");
    stack.push("C++");
    stack.push("C");
    stack.push("Python");
    stack.push("JavaScript");

    System.out.println(stack);

    // removing element from stack
    stack.pop();
    System.out.println(stack);
  }
}

// Output
// [Java, C++, C, Python, JavaScript]
// [Java, C++, C, Python]

Set Interface in Java

It is a collection of unique elements i.e., duplicate elements are not stored. Insertion order is not preserved. The classes that implement the Set Interface are HashSet, LinkedHashSet, and TreeSet.

Now, let’s see the classes implementing Set Interface.

HashSet in Java

It uses a hash table to store the elements with the technique of hashing. It implements the Set Interface.

Syntax
HashSet<dataType> hashset_name=new HashSet<>();

import java.util.*;
public class HashSetExample {
    public static void main(String []array){
    HashSet<Integer> hashset=new HashSet<>();

    // adding elements in hash set
    hashset.add(5);
    hashset.add(16);
    hashset.add(8);
    hashset.add(9);
    hashset.add(-3);
    // storing 16 again
    hashset.add(16);

    System.out.println(hashset);

    // removing element
    hashset.remove(-3);
    System.out.println(hashset);
  }
}

// Output
// [16, -3, 5, 8, 9]
// [16, 5, 8, 9]

In the above example, we have inserted 16 twice but it is not stored again.

LinkedHashSet in Java

It is a Hash table and implements Set interface and extends HashSet class. It does not allow storing null value.

Syntax
LinkedHashSet<dataType> linkedHash_Name=new LinkedHashSet<>();

import java.util.*;
public class LinkedHashSetExample{
    public static void main(String []array){
    LinkedHashSet<String> web=new LinkedHashSet<>();

    // adding elements in linked hash set
    web.add("HTML");
    web.add("CSS");
    web.add("Javacript");
    web.add("PHP");
    web.add("MYSQL");

    System.out.println(web);
  }
}

// Output
// [HTML, CSS, Javacript, PHP, MYSQL]

TreeSet in Java

It uses a red-black tree to store elements and implements Set interface. The elements are stored in ascending order in TreeSet. The access and retrieval times for the Java TreeSet class are quite fast.

Syntax
TreeSet<dataType> treeSet_Name=new TreeSet<>();

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

    TreeSet<String> tree=new TreeSet<String>();

    tree.add("HTML");
    tree.add("PHP");
    tree.add("Python");
    // storing html again
    tree.add("HTML");

    System.out.println(tree);
    tree.remove("PHP");
    System.out.println(tree);
  }
}

// Output
// [HTML, PHP, Python]
// [HTML, Python]

Queue Interface in Java

It implements the queue data structure in which works on the concept of FIFO (First In First Out) which means that The element that is inserted first will be the first to be deleted. PriorityQueue, Deque, and ArrayDeque are the classes that implement the Queue interface.
Given below are the lists of classes implementing the Queue interface:

PriorityQueue

Each element is given some priority and based on this priority the element is processed.

Syntax
PriorityQueue <dataType> queueName=new PriorityQueue<>();

import java.util.*;
public class PriorityQueueExample
  {
     public static void main(String[] array) {
     PriorityQueue<String> queue=new PriorityQueue<String>();

     queue.add("html");
     queue.add("css");
     queue.add("javascript");
     queue.add("php");
     queue.add("python");

     System.out.println(queue);

     System.out.println("head:"+queue.element());
     System.out.println("head:"+queue.peek());

     queue.remove();
     queue.poll();
     System.out.println(queue);
  }
}

//Output
// [css, html, javascript, php, python]
// css
// css
// [javascript, php, python]

Deque Interface in Java

A double-ended queue is referred to as Deque. It allows performing insertion and deletion from both ends. The class that implements the Deque interface is ArrayDeque.

ArrayDeque

Syntax
ArrayDeque<dataType> dequeName = new ArrayDeque<>();

import java.util.*;
public class DequeExample
  {
     public static void main(String[] array) {
     ArrayDeque<Integer> deque = new ArrayDeque<>();
     deque.add(1);
     deque.add(-4);
     deque.add(5);
     System.out.println(deque);
  }
}

//Output
// [1, -4, 5]

Now, let’s see one program to store the details of employees using collections.

How to write a Java program for employee details using collection?

In this program, I will be storing details of an employee using ArrayList. You can use any other collection to store it.

import java.util.*;
class Employee{
    private int id,age;
    private float Salary;
    private String name, gender,address;

    public Employee(){
    id=age=0;
    Salary=0;
    name=gender=address="";
    }
public void setDetails(String name, int id, int age, String gender, String address, float Salary) {
    this.name=name;
    this.id=id;
    this.age=age;
    this.gender=gender;
    this.address=address;
    this.Salary=Salary;
    }
    public void getDetails(){
    System.out.println("Employee ID: "+id);
    System.out.println("Employee Name: "+name);
    System.out.println("Gender: "+gender);
    System.out.println("Age: "+age);
    System.out.println("Address: "+address);
    System.out.println("Salary: "+Salary);
    }
}
public class Main
{
  public static void main(String[] array) {

  ArrayList<Employee> employee=new ArrayList<>();

  Employee raman=new Employee();
  raman.setDetails("Raman Gupta", 101, 25,"Male","XYZ Pune", 30000);
  employee.add(raman);

  Employee neha=new Employee();
  neha.setDetails("Neha Sharma", 103, 23,"Female","102 ABC, Kanpur", 35000);
  employee.add(neha);

  System.out.println("******Employee Details**********");
  for(Employee e:employee){
  e.getDetails();
  }
}
}

// Output
// ******Employee Details**********
// Employee ID: 101
// Employee Name: Raman Gupta
// Gender: Male
// Age: 25
// Address: XYZ Pune
// Salary: 30000.0
// Employee ID: 103
// Employee Name: Neha Sharma
// Gender: Female
// Age: 23
// Address: 102 ABC, Kanpur
// Salary: 35000.0

I hope you now have a good understanding of Collections in Java Programming. There are many others methods of collection interfaces and classes but they cannot be discussed in a single module. Keep in touch with us if you’d like to learn more topics like this.