top

Search

Java Tutorial

.

UpGrad

Java Tutorial

Java Collection

Introduction 

Java is one of the major programming languages, with more than 33.27% of users around the globe. Developed in 1991 by James Gosling of Sun Microsystems, Inc., this language quickly grew a user base and boasted a rich system. 

Java collections offer a one-stop destination for all sorts of data manipulation tasks. It is an all the more perfect opportunity to start learning the language.

If you're looking at Java collection framework notes, you've landed at the right place. This tutorial will examine how to utilize best practices using the Java framework. 

While working on the Java collection library, we'll employ the latest developments and ensure better learning of Java. Let's begin our journey into Java's collection framework in depth.

Overview 

The Java collection framework is a set of interfaces and classes working to offer a unified front. This framework works towards storing and manipulating collections of objects. 

One of the essentials of the Java language, it provides the interface for several data structures. These include lists, maps, sets, and queues. Classes involve ArrayList, PriorityQueue, TreeSet, Vector, and others.

What is a Collection in Java? 

A Java collection is a group of objects that represent a single unit. It is based on a framework that offers a network to store and manipulate data as a group of objects. Its features include:

  • Java collection inhibits several collection interfaces like ArrayList, TreeSet, LinkedList, Vector, and HashSet.

  • You can find the collection classes in Java.util package.

  • The collection interface (Java.util.collection) defines popular methods like add, remove, contain, and vice versa.

  • Another root interface is the Map in Java collections (Java.util.Map).

What is Java Collections Framework?

The Java Collections Framework is a set of classes and interfaces containing popular data structures. It was introduced to allow coders to work with different types of collections depending on their immediate needs. 

The Java collection framework is designed to carry out simple tasks such as sorting and searching. These include lists, sets, queues, deques, and maps. Much like the list interface, the map interface offers methods for adding, removing, and searching pairs. 

It is a core portion of Java, and the 'Collection Framework' can be found in JDK 1.2.

Need for a Separate Collection Framework

As Java was still in its initial stages, the Java collections weren't accessible back in 1998. As the collection framework was incredibly complicated, and it was difficult in the first release. Additionally, the language designers wanted to test and debug before introducing complex features. 

With the release of JDK 1.2 and Java.util package containing the tools, the Java Collection Framework was ready for users. 

Differences between the Collection and Collections Framework

Collection

Collection Framework


The collection is an interface.

The collections framework is a library.

The collections interface represents a group of objects.

The collections framework consists of a set of classes and interfaces.

The collections interface offers a basic set of operations such as add(), remove(), contains(), etc.

The collections framework offers a more complicated operations like sorting, shuffling, searching, and reversing.


It can be used with a single object type.

The collections framework works with different types of objects.

It provides fundamentals for manipulating content in a collection.

The collection framework deals with a list of advanced methods for content manipulation.

Advantages of the Collection Framework 

The collection framework is a versatile library that offers the following advantages -

  • Uniform and consistent API - The collections framework increases the overall performance implementation of algorithms and data structures. 

It maintains a set of interfaces like Set, Collection, Map, and List, along with the classes (ArrayList, Vector, LinkedList) for carrying out the implementations.

  • Lessened effort of programming - A programmer is least concerned with how collections are structured with the collections framework. 

It encourages object-oriented programming or abstraction. Simultaneously, it can help them focus on utilizing the other parts of the program.

  • Enhances performance - The quality and speed of the program can significantly benefit from the implementations. 

With the collections framework, a programmer doesn't have to consider implementing a data structure anymore. Instead, they can utilize the most effective performance, drastically improving speed and quality.

Hierarchy of the Collection Framework 

The collection framework is based on a hierarchical structure of classes and interfaces. It is organized into two branches - the map and the collection branches.

The map branch is divided into Mapo, SortedMap, and NavigableMap interfaces, which store key-value data.

The collection branch is divided into Set, List, and Queue interfaces, which store data similarly.

There are specialized collection classes like Vector and Hashtable, which provide high-performance implementations.

Methods of the Collection Interface

Some standard collection interfaces are: 

1. add() - It adds an object to the existing collection.

2. remove() - It adds elements in the existing collection to the collection.

3. contains() - This method determines whether the collection contains an element.

4. size() - It returns the total number of elements in the collection.

5. spiterator() - It creates a Spliterator over the elements.

6. toArray() -It returns an array of all collection elements.

7. clear() - It removes every element from the collection.

8. stream() - It returns a sequential stream as a source.

9. retainAll() - It retains only specific elements in a collection.

10. removeAll() - It removes every oa collection.

11. equals() - It compares specified objects based on equality.

12. hashCode() - It returns the hash code for each collection.

Interfaces that extend the Collections Interface

  • Iterable Interface 

An iterable interface is an object where the elements can be accessed sequentially. 

Iterator iterator(); 
  • Collection Interface

A collection interface is an object divided into an array, set, list, or Map.

interface Collection<E>
  •  List Interface 

The list interface is an abstract data type specifying listicle operations.

interface [interface-name] {
    [interface-properties]
};

Classes that implement the List Interface

The collection framework works with several classes, which are demonstrated below:

1. ArrayList 

The ArrayList works like an array. It can dynamically grow and shrink per the requirement of the programmer.

import java.util.*;

class MyArrayList {
  public static void main(String[] args) {
    ArrayList<String> myStrings = new ArrayList<String>(); // Creating ArrayList
    myStrings.add("Alice"); // Adding object in ArrayList
    myStrings.add("Roland");
    myStrings.add("Anny");
    myStrings.add("Charlie");
    // Traversing ArrayList through Iterator
    Iterator<String> iterator = myStrings.iterator();
    while (iterator.hasNext()) {
      System.out.println(iterator.next());
    }
  }
}

2. LinkedList  

The LinkedList stores data linearly. It works with the help of nodes connected like pointers and can store a large amount of data.

import java.util.*;

public class MyLinkedList {
  public static void main(String[] args) {
    LinkedList<String> myStrings = new LinkedList<String>(); // Creating LinkedList
    myStrings.add("Brianne"); // Adding object in LinkedList
    myStrings.add("Bart");
    myStrings.add("Archie");
    myStrings.add("Garry");
    Iterator<String> iterator = myStrings.iterator(); // Traversing LinkedList through Iterator
    while (iterator.hasNext()) {
      System.out.println(iterator.next());
    }
  }
}

3. Vector 

Vector allows for storage and retrieval of data in a compact form. 

import java.util.*;

public class MyVector {
  public static void main(String[] args) {
    Vector<String> myStrings = new Vector<String>(); // Creating Vector
    myStrings.add("Mert"); // Adding object in Vector
    myStrings.add("Ashley");
    myStrings.add("Bob");
    myStrings.add("Barry");
    Iterator<String> iterator = myStrings.iterator(); // Traversing Vector through Iterator
    while (iterator.hasNext()) {
      System.out.println(iterator.next());
    }
  }
}

4. Stack  

Stack comes under Vector and a legacy class and employs the last-in-first-out concept.

import java.util.*;

public class MyStack {
  public static void main(String[] args) {
    Stack<String> myStack = new Stack<String>(); // Creating Stack
    myStack.push("Tina"); // Adding object in Stack
    myStack.push("Alexa");
    myStack.push("Mary");
    myStack.push("John");
    myStack.pop();
    Iterator<String> iterator = myStack.iterator(); // Traversing Stack through Iterator
    while (iterator.hasNext()) {
      System.out.println(iterator.next());
    }
  }
}

5. Queue Interface  

The queue interface is also based on the FIFO principle and is akin to a real-world queue line.

Queue<String> q1 = new PriorityQueue();  
Queue<String> q2 = new ArrayDeque();  

a) Priority Queue 

A priority queue is a type of data structure in which each element has priority.

import java.util.*;

public class MyPriorityQueue {
  public static void main(String[] args) {
    PriorityQueue<String> myQueue = new PriorityQueue<String>(); // Creating PriorityQueue
    myQueue.add("Kim"); // Adding object in PriorityQueue
    myQueue.add("Jimmy");
    myQueue.add("Jack");
    myQueue.add("George");
    System.out.println("head:"+myQueue.element());
    System.out.println("head:"+myQueue.peek());
    System.out.println("iterating the queue elements:");
    Iterator<String> iterator = myQueue.iterator(); // Traversing PriorityQueue through Iterator
    while (iterator.hasNext()) {
      System.out.println(iterator.next());
    }
    myQueue.remove();
    myQueue.poll();
    System.out.println("after removing two elements:");
    Iterator<String> iterator2 = myQueue.iterator();
    while (iterator2.hasNext()) {
      System.out.println(iterator2.next());
    }
  }
}

6. Deque Interface  

The deque interface allows for easy adding and removal of elements from both ends of a queue.

Deque d = new ArrayDeque();  

a) Array Deque

An array queue stores objects in a double-ended queue or deque.

import java.util.*;

public class MyDeque {
  public static void main(String[] args) {
    Deque<String> myDeque = new ArrayDeque<String>(); // Creating Deque and adding elements
    myDeque.add("Jenny");
    myDeque.add("Kate");
    myDeque.add("Alex");
    // Traversing elements
    for (String str : myDeque) {
      System.out.println(str);
    }
  }
}

7. Set Interface  

A set interface is an unordered collection of objects that does not allow duplicate values to be stored.

Set<data-type> s1 = new HashSet<data-type>();  
Set<data-type> s2 = new LinkedHashSet<data-type>();  
Set<data-type> s3 = new TreeSet<data-type>();  

Classes that implement the Set Interface

The following classes implement the Set interface: 

1. Hash Set 

A hash set is a type of data structure that stores and retrieves data in an unorganized manner. It does not maintain an ordering over its elements.

import java.util.*;  

public class TestJavaCollection7{  
public static void main(String args[]){  
//Creating HashSet and adding elements  
HashSet<String> set=new HashSet<String>();  
set.add("Stella");  
set.add("Robert");  
set.add("Kevin");  
set.add("Ben");  
//Traversing elements  
Iterator<String> itr=set.iterator();  
while(itr.hasNext()){  
System.out.println(itr.next());  
}  
}  
}  

2. Linked Hash Set

The LinkedHashSet has the same characteristics as a HashSet. However, it is different because it uses a doubly linked list to store data and retain elements.

import java.util.*;

public class MyLinkedHashSet {
  public static void main(String[] args) {
    LinkedHashSet<String> mySet = new LinkedHashSet<String>(); // Creating LinkedHashSet
    mySet.add("Arun"); // Adding elements in LinkedHashSet
    mySet.add("Vineet");
    mySet.add("Abhishek");
    mySet.add("Sapna");
    Iterator<String> iterator = mySet.iterator(); // Traversing LinkedHashSet through Iterator
    while (iterator.hasNext()) {
      System.out.println(iterator.next());
    }
  }
}

3. Sorted Set Interface  

A set interface provides a set of methods for operations on a set for sorting a specific order.

SortedSet<data-type> set = new TreeSet();  

The class implementing the sorted set interface is TreeSet. 

i) Tree Set 

A TreeSet is a collection of elements in a tree-like structure. It is similar to a HashSet, but it stores elements ascendingly.

import java.util.*;

public class TestJavaCollection9 {
  public static void main(String args[]) {
    // Creating and adding elements
    TreeSet<String> set = new TreeSet<String>();
    set.add("Chris");
    set.add("Raj");
    set.add("Albin");
    set.add("Rahul");
    // Traversing elements
    Iterator<String> itr = set.iterator();
    while (itr.hasNext()) {
      System.out.println(itr.next());
    }
  }
}

4. Map Interface  

The map interface utilizes an object that maps keys to values. It isn't a subtype of the collection interface.

The frequently used implementation of a Map interface is a HashMap. 

i) Hash Map  

HashMap utilizes a hash table for storing data. It holds key-value pairs and uses a hash key for accessing the element.

import java.util.*;

public class HashMapDemo {
public static void main(String[] args) {
  // Create a hash map
  HashMap<String, Double> accountBalances = new HashMap<String, Double>();
  // Put elements to the map
  accountBalances.put("Akash", new Double(3434.34));
  accountBalances.put("Manish", new Double(123.22));
  accountBalances.put("Arya", new Double(1378.00));
  accountBalances.put("Suman", new Double(99.22));
  accountBalances.put("Zainab", new Double(-19.08));
  // Get a set of the entries
  Set<Map.Entry<String, Double>> entries = accountBalances.entrySet();
  // Get an iterator
  Iterator<Map.Entry<String, Double>> iterator = entries.iterator();
  // Display elements
  while(iterator.hasNext()) {
     Map.Entry<String, Double> entry = iterator.next();
     System.out.print(entry.getKey() + ": ");
     System.out.println(entry.getValue());
  }
  System.out.println();
  // Deposit 1000 into Akash account
  double balance = accountBalances.get("Akash").doubleValue();
  accountBalances.put("Akash", new Double(balance + 1000));
  System.out.println("Akash’s new balance: " + accountBalances.get("Akash"));
}
}

Conclusion 

The Java collections are an invaluable tool for developers. They are helpful as they offer a powerful and efficient way of managing data collection. 

Java collection's multi-level approach helps developers save time and effort when programming. It consists of multiple valuable data structures that can store and manage data according to a programmer's needs. 

Knowing Java collections is essential for a developer who wants to make the most out of their code while, at the same time, also saving up on time.

FAQs 

1. Which is the fastest collection in the Java collections framework?

The HashSet collection is the fastest in Java. In the same way, the LinkedHashSet collection is an excellent asset to developers looking to insert the order of elements.

2. How is a collection different from collections?

A collection is a unified interface, whereas collections form a class of objects.

3. Which are the top collection types in the Java framework?

The linear format, namely ArrayList and LinkedList, are the most comprehensive collection types in the Java framework.

Leave a Reply

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