Collections in java

Collections in Java

Collections in java refer to a group of objects. It is a type of framework which provides a store for the grouping of objects. There are certain operations performed under collections in java such as merging, sorting, manipulation, deletion, insertion, searching etc. Java collection framework provides a built structure representing various classes and interfaces. It works on the basis of specific algorithms with proper interfaces and implementation of classes.

Java Collections Methods

S.NoMethodDescription
1.public boolean add()We use this method to insert an element in the collection
2.public boolean addAll()We use this method to insert a specific element in the collection
3.public boolean remove()We use this method to delete an element from the collection
4.default boolean remove()We use this method to delete all elements from the collection
5.public boolean retainAll()It is used to delete all the elements from the collection except for some specific collection.
6.public int size()This method will return the total size of the collection.
7.public void clear()This method clears all the elements from the collection.
8.default boolean contains()we use this method to search an element from the collection.
9.default boolean containsAll()we use this method to search a specific element from the collection.
10.public convert[] to Array()This method will convert the whole collection into an array.
11.public boolean isEmpty()This method will check if the collection is empty.
12.public boolean equals()This method will match the two collections.
13.public int hashCode ()This will return the hash code of the collection

We have a number of advantages of collection framework. Go through the following points to know the advantages of collection.

Best Laptops for Programmers

ITEMSPRICE
Click here for Price
Click here for Price
Click here for Price

What are Collections in Java

  • Collections in java have a consistent set of methods such as APIs, sets, lists, arrays, maps etc.
  • A user never has to worry about the design of the collection framework. While using collections, he can easily worry about the program he is designing. As a result, in object-oriented programming, the concept of abstraction is implemented successfully.
  • The use of collection helps in increasing the performance and making it reach a high level. A user never has to think twice about how to use specific data structures in Java. He can simply choose an algorithm from the collection in java and has fruitful results.

What is the Use of collections in java?

  • When the user works with collection in java, the programming effort is reduced.
  • The formation of programs and algorithms using java collection is much easier for the programmer.

Which is the Best Collection in Java?

  • The collection helps the user is concentrating on the important parts of the program.
  • Hashmap/ HashSet is the best collection in java as it gives the best performance with less effort.

To understand more about collection interface, we need to throw light on list interface.

List interface: It is also said to be the child interface of the Collection interface. List stores all the ordered elements of the collection. It allows keeping duplicate data in it. So on the list, it is possible for the user to implement vector, stack, ArrayList etc.

How to create a List in java

List <L> al = new ArrayList<>();

List <L> Il = new LinkedList<>();

List <L> m = new Vector<>();

Where we denote they type of object with L.

There are a number of classes in list interface. Let us discuss them in the next section:

List Interface in Java

List can also be called the child of collection interface. it is a type of collection which stores the sorted list of elements in it. it can contain duplicate values as well. It has 3 sub-lists which are ArrayList, LinkedList and vector.

ArrayList Class

ArrayList has a number of dynamic arrays which are assumed to be slower than the usual arrays. Though, they are a lot helpful when we see through the context of programming as a user needs a lot of manipulation. We cannot use ArrayList for usual data types such as int, char, float etc. For such cases, we need to bring wrapper class into the picture. If a collection grows, the size of the ArrayList is increased automatically. Similarly, if a collection shrinks, the size of the ArrayList is decreased automatically. Check out the java program below to understand ArrayList.

import java.util.ArrayList;

public class DeveloperHelps {
  public static void main(String[] args) {
    ArrayList<String> fruits = new ArrayList<String>();
    fruits.add("apple");
    fruits.add("banana");
    fruits.add("mango");
    fruits.add("kiwi");
    System.out.println(fruits);
  }
}


The output of this program is:

[apple, banana, mango, kiwi]

LinkedList Java Class

As we are aware of the fact that the linked list in data structures are the data types that stores elements in contiguous memory locations. Every element in the linked list is also known as a node. So, every element has its own space and address part in the linked list. The linked list clearly links the elements using pointers and their address pointing towards the next element. Below is the code for understanding linked list in java:

public class DeveloperHelps {    
class Node{    
int data;    
Node next;    
public Node(int data) {    
this.data = data;    
this.next = null;    
}    
}    
public Node head = null;    
public Node tail = null;    
public void addNode(int data) {    
Node newNode = new Node(data);    
if(head == null) {    
head = newNode;    
tail = newNode;    
}    
else {    
tail.next = newNode;    
tail = newNode;    
}    
 }    
public void display() {    
Node current = head;    
if(head == null) {    
System.out.println("The list is empty");    
return;    
}    
System.out.println("Nodes of linked list are: ");    
while(current != null) {    
System.out.print(current.data + " ");    
current = current.next;    
}    
System.out.println();    
}    
public static void main(String[] args) {    
DeveloperHelps sList = new DeveloperHelps();    
sList.addNode(10);    
sList.addNode(20);    
sList.addNode(30);    
sList.addNode(40);    
sList.display();    
    }    
}   


The output of the above linkedlist program in java is:

Nodes of linked list are: 
10 20 30 40 

Vector Class Java

A vector is called when the user is in need of dynamic arrays. It is much identical to the array list only. The main difference between a vector list and an array list is that a vector list is synchronized whereas an array list is not. Check out the program below to understand vector in java:

import java.util.*;

public class DeveloperHelps {
public static void main(String args[]) {
Vector<String> vec = new Vector<String>(2);
vec.addElement("Kiwi");
vec.addElement("Apple");
vec.addElement("Mango");
System.out.println("Size is: "+vec.size());

vec.addElement("fruit1");
vec.addElement("fruit2");
vec.addElement("fruit3");
System.out.println("Size after addition of element: "+vec.size());
System.out.println("Capacity after increment is: "+vec.capacity());
Enumeration en = vec.elements();
      System.out.println("\nElements are:");
      while(en.hasMoreElements())
         System.out.print(en.nextElement() + " ");
   }
}


The output of the following program will be:

Size is: 3
Size after addition of element: 6
Capacity after increment is: 8

Elements are:
Kiwi Apple Mango fruit1 fruit2 fruit3

Java Stack

A stack is based on last in first out principle as we discussed earlier in the article. We can also say that stack is a subclass of the vector. For more details regarding stack, click here.

Queue Interface in Java

Unless stacks, queues maintain first in first out. It means the element pushed first in the queue will be out in the first place only. The order of elements matters in queue data structures. For example, in a movie ticket line, the person who goes first in the queue is served first then the person who entered late. This is the main difference between queues and stacks. A queue has the following three interfaces which it can extend. It has further 3 sub-queues which are priority queue, dequeue and array queue.

Priority Queue

In a priority queue, the objects are moved on the basis of their priority. Even if the queue follows first in first out, the elements move according to the priorities that they have. It works according to the priority heap. If elements in a priority queue are not assigned any priorities, they move according to the assigned values.

Java Program to understand Priority queue

import java.util.PriorityQueue;
public class DeveloperHelps {
public static void main(String[] args) {
  PriorityQueue<String> queue1 = new PriorityQueue<String>();  
  queue1.add("Pink");
  queue1.add("Red");
  queue1.add("Yellow");
  System.out.println("Colours in Priority Queue 1: "+queue1);
  PriorityQueue<String> queue2 = new PriorityQueue<String>();  
  queue2.add("Mango");
  queue2.add("Cherry");
  queue2.add("Apple");
  System.out.println("Fruits in Priority Queue 2: "+queue2);
queue1.addAll(queue2);
System.out.println("New Priority Queue1: "+queue1);
 }
}


The output of the above program will be:

Colours in Priority Queue 1: [Pink, Red, Yellow]
Fruits in Priority Queue 2: [Apple, Mango, Cherry]
New Priority Queue1: [Apple, Mango, Cherry, Red, Pink, Yellow]

Deque Interface

The full form of deque is double ended queue.This also meansa data structure in which we can add elements and from which we can remove elements from both the ends of the queue. Deque is a sub file of queue interface.

Check out the program below to understand deque collection in java:

import java.util.*;  
public class DequeExample {  
public static void main(String[] args) {  
    Deque<String> deque=new ArrayDeque<String>();  
    deque.offer("arvind");  
    deque.offer("vimal");  
    deque.add("mukul");  
    deque.offerFirst("jai");  
    System.out.println("After offerFirst Traversal...");  
    for(String s:deque){  
        System.out.println(s);  
    }  
    //deque.poll();  
    //deque.pollFirst();//it is same as poll()  
    deque.pollLast();  
    System.out.println("After pollLast() Traversal...");  
    for(String s:deque){  
        System.out.println(s);  
    }  
}  
}


The output of the above program will be:

The deque list is
Om
Megha
Varun
Ravina
The final sorted list will be
Om
Megha
Varun

ArrayDeque

With the help of ArrayDeque, the user is able to design a collection with resizable array. It allows the programmer to add or remove the elements from both sides of the queue. As we know that arrays have no space constraints, so they grow as much as needed for the elements.

Check out the program below to understand ArrayDeque in java:

import java.util.*;    
class Book {    
int id;    
String name,author,publisher;    
int quantity;    
public Book(int id, String name, String author, String publisher, int quantity) {    
    this.id = id;    
    this.name = name;    
    this.author = author;    
    this.publisher = publisher;    
    this.quantity = quantity;    
}    
}    
public class DeveloperHelps {    
public static void main(String[] args) {    
    Deque<Book> set=new ArrayDeque<Book>();    
      
    Book b1=new Book(101,"Java programming","A","B",7);    
    Book b2=new Book(102,"Java programming 2","C","D",4);    
    Book b3=new Book(103,"Java programming  3","E","F",6);    
     
    set.add(b1);    
    set.add(b2);    
    set.add(b3);    
     
    for(Book b:set){    
    System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);    
    }    
}    
} 


The output of the above program will be:

101 Java programming A B 7
102 Java programming 2 C D 4
103 Java programming  3 E F 6

Java Sets Interface

This interface is present in java in java.util package. It is a subcategory of the collection interface which has unsorted elements in it. Java Set cannot contain duplicate values int it but can have null values in it. It has subsets that are sorted set, tree set, hash set and linked HashSet.

Sorted Set

It is just like the set interface which helps in the proper ordering of the elements. The elements are always arranged in the increasing order, hence a sorted set provides a natural ordering of the elements. The program below will help you in better understanding of sorted set in java:

import java.util.*;
public class DeveloperHelps {
public static void main(String[] args) {
SortedSet set = new TreeSet(); 
set.add("Name 1");
set.add("Name 2");
set.add("Name 3");
Iterator it = set.iterator();
while (it.hasNext()) {
Object element = it.next();
System.out.println(element.toString());
      }
   }
}


The output of the above program will be:

Name 1
Name 2
Name 3

Tree Set

This set has a tree structure for the storage of elements. It has unique elements similar to the hash set. The advantage of using tree set is that the execution of processes on the elements is faster in this interface. tree structure always stores the elements in ascending order. The program below will help you in better understanding of tree set in java:

import java.util.*;
public class DeveloperHelps {

   public static void main(String args[]) {
      
      TreeSet ts = new TreeSet();
      ts.add("Name 1");
      ts.add("Name 2");
      ts.add("Name 3");
      ts.add("Name 4");
      ts.add("Name 5");
      ts.add("Name 6");
      System.out.println(ts);
   }
}


The output of the above TreeSet program will be:

[Name 1, Name 2, Name 3, Name 4, Name 5, Name 6]

HashSet

This set has operations like add, remove, contains, size etc and provides better performance than the tree set. Though, it doesn’t have default ordering of the elements, but has lower cost than the tree set. As the name says, it has a hash map for the representation of the collection of elements. The process of storing elements in the hashset is also known as hashing. The program below will help you in better understanding of Hashset in java:

import java.util.HashSet;

public class DeveloperHelps {
  public static void main(String[] args) {
    HashSet<String> fruits = new HashSet<String>();
    fruits.add("Mango");
    fruits.add("Apple");
    fruits.add("Kiwi");
    fruits.add("Cherry");
    fruits.add("Banana");
    System.out.println(fruits);
  }
}


The output of the above program will be:

[Apple, Kiwi, Cherry, Mango, Banana]

Linked Hashset

This set is the representation of collection in the form of linked list. It performs operations such s insertion and contains unique elements. As a result, it doesn’t allow duplicate values in it. It is similar to the hashset which allows null values in it. The program below will help you in better understanding of Linked hashset in java:

import java.util.LinkedHashSet;
public class LinkedHashSetExample {
public static void main(String args[]) {
         LinkedHashSet<String> lhset = new LinkedHashSet<String>();
         lhset.add("Name 1");
         lhset.add("Name 2");
         lhset.add("Name 3");
         lhset.add("Name 4");
         lhset.add("Name 5");
         lhset.add("Name 6");
         System.out.println(lhset);
        LinkedHashSet<Integer> lhset2 = new LinkedHashSet<Integer>();
         lhset2.add(1);
         lhset2.add(2);
         lhset2.add(3);
         lhset2.add(4);
         lhset2.add(5);
         lhset2.add(6);
         System.out.println(lhset2);
    }
}


The output of the above program will be:

[Name 1, Name 2, Name 3, Name 4, Name 5, Name 6]
[1, 2, 3, 4, 5, 6]

Java Map Interface

In this interface, a key value is linked to the data of the interface. It stores data in keys with its values. The map interface also introduces a concept called hashing in which a large string is converted to a small string. This process helps in making the indexing faster. There are three sub-interfaces of maps in java. They are HashMap, TreeMap and LinkedHashMap. Let us discuss more about these sub categories of map interface:

HashMap: It is basically an advanced version of hashtable which allows multiple null key values. A hashmap maintains no kind of order of elements or of the mapping. HashMap is a fail-fast in java which means a system in java which tends to fail immediately when an error occurs. Hashmap throws a ConcurrentModificationException in case an error is about to occur. This problem only occurs because an iterator works in the case of HashMap rather than an enumerator.

TreeMap: A TreeMap in java contains values linked to keys in sorted fashion. It contains unique elements and cannot possess a single null key value. Though it can have multiple null key values supporting non synchronous behaviour. TreeMap will always maintain the element sorting in the form of ascending order.

LinkedHashMap: This sub category extends Java HashMap implementing a map interface. It also contains values which are based on keys. It possesses unique elements maintaining the sequence of elements in the form of insertion sort. The difference between HashMap and LinkedHashMap is that a Hashmap provides quick searching, insertion as well as deletion. Whereas a linkedHashMap maintains a track and provides the order of insertion which a HashMap does not provide. Hence, the elements can always be accessed in the form of insertion sort.

Summary:

  • Java collections has certain algorithms
  • It works on the basis of interfaces as well as implementations of classes.
  • It has a number of functions that can be performed on the objects.

Leave a comment

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

Discover Our Exciting Courses and Quiz

Enroll now to enhance your skills and knowledge!

Java Online Quiz

Level up your coding skills with our interactive programming quiz!