Collections in Java

Shubham Bhurke
9 min readSep 15, 2023

--

  1. The Collections in Java is a Framework provided to store and manipulate group of objects. Java Collection means a single unit of objects.
  2. Java Collection Framework provides interfaces like- Set, List, Queue, Dequeue and Classes like- ArrayList, Vector, LinkedList, Priority Queue, HashSet, LinkedHashSet, TreeSet.

Collection Framework

Collection Framework represents a unified architecture for Sorting and Manipulating a group of objects. It includes-

  1. Interfaces and it’s implementations, i.e., classes
  2. Algorithm

Note- The java.util package contains all the classes and interfaces for the Collection framework.

Methods of Collection Interface

List Interface

  1. List represents a list type data structure which is used to store an ordered collection of objects.
  2. Can have duplicate values.
  3. It is implemented by classes like-

ArrayList

LinkedList

Vector

Stack

Syntax-

List <data-type> list1= new ArrayList();
List <data-type> list2 = new LinkedList();
List <data-type> list3 = new Vector();
List <data-type> list4 = new Stack();

ArrayList

  1. Array List uses a dynamic array to store the duplicate element of any different data types.
  2. ArrayList class maintains the insertion order and is non-synchronized.
  3. Elements stored in the ArrayList can be accessed randomly.

Example-

import java.util.*;
class TestJavaCollection1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add("Ravi");//Adding object in arraylist
list.add("Vijay");
list.add("Ravi");
list.add("Ajay");
//Traversing list through Iterator
Iterator itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
Ravi
Vijay
Ravi
Ajay

LinkedList

  1. Uses a Doubly Linked List internally to store the elements.
  2. Maintains insertion order and is not synchronized.
  3. Manipulation is fast as no shifting is required.

Example:

import java.util.*;
public class TestJavaCollection2{
public static void main(String args[]){
LinkedList<String> al=new LinkedList<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
Ravi
Vijay
Ravi
Ajay

Vector

  1. Vector uses Dynamic Array to store the data elements.
  2. Similar to Array List.
  3. Vector is synchronized.

Example-

import java.util.*;
public class TestJavaCollection3{
public static void main(String args[]){
Vector<String> v=new Vector<String>();
v.add("Ayush");
v.add("Amit");
v.add("Ashish");
v.add("Garima");
Iterator<String> itr=v.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
Ayush
Amit
Ashish
Garima

Set Interface

  1. Present in java.util package.
  2. Extends the Collection Interface.
  3. Represents an unordered set of elements.
  4. Duplicates cannot be stored.
  5. We cannot store more than one NULL Value.
  6. Set is implemented by-

HashSet

LinkedHashSet

TreeSet

Syntax to declare Sets-

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

HashSet

  1. HashSet Class implements Set Interface.
  2. Represents a collection that uses a hash table for storage.
  3. Contains unique items.
  4. As the name suggests, Hashing technique is used to store the elements in the HashSet.
  5. In Hashing technique each element in the Set is assigned with a unique hash based on its content. This technique is very useful in identifying duplicates where elements with the same hash values are considered to be duplicate. This way, duplicates are eliminated from HashSet.

Example:

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("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
//Traversing elements
Iterator<String> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
Vijay
Ravi
Ajay

LinkedHashSet

  1. Represents the LinkedList implementation of Set Interface.
  2. Extends the HashSet class and implements Set interface.
  3. Contains unique items only.
  4. Maintains insertion order and permits null values.
  5. No duplicates. Follows Set principles.

Example:

import java.util.*;
public class TestJavaCollection8{
public static void main(String args[]){
LinkedHashSet<String> set=new LinkedHashSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
Iterator<String> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
Ravi
Vijay
Ajay

SortedSet

  1. SortedSet is the alternative to the Set interface.
  2. Provides ordering on its elements by default.
  3. Elements are Sorted in Ascending order.

Syntax-

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

TreeSet

  1. TreeSet implements the Set Interface which uses Tree for Storage.
  2. Contains unique elements.
  3. Access and retrieval of elements is fast.
  4. Elements in TreeSet are sorted in Ascending Order.

Example-

import java.util.*;
public class TestJavaCollection9{
public static void main(String args[]){
//Creating and adding elements
TreeSet<String> set=new TreeSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
//traversing elements
Iterator<String> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
Ajay
Ravi
Vijay

In the above example, You can see that the elements were inserted in a different order but the TreeSet automatically arranged the elements in alphabetical order.

HashSet Class

  1. Used to create a collection that uses a hash table for Storage.
  2. Inherits Abstract class and implements Set interface.
  3. Contains unique elements only.
  4. Stores elements by hashing technique.
  5. Allows Null value.
  6. HashSet class is not synchronized i.e does not maintain insertion order. Elements are inserted on basis of their hash code.
  7. Best for Search operations as it is faster.
  8. Default capacity of HashSet is 16, and the Load Factor is 0.75.

HashSet Class Declaration

Syntax-

public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable, Serializable

Example-

import java.util.*;
class HashSet2{
public static void main(String args[]){
//Creating HashSet and adding elements
HashSet<String> set=new HashSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
//Traversing elements
Iterator<String> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
Ajay
Vijay
Ravi

Java Hashset example to remove elements-

import java.util.*;
class HashSet3{
public static void main(String args[]){
HashSet<String> set=new HashSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Arun");
set.add("Sumit");
System.out.println("An initial list of elements: "+set);
//Removing specific element from HashSet
set.remove("Ravi");
System.out.println("After invoking remove(object) method: "+set);
HashSet<String> set1=new HashSet<String>();
set1.add("Ajay");
set1.add("Gaurav");
set.addAll(set1);
System.out.println("Updated List: "+set);
//Removing all the new elements from HashSet
set.removeAll(set1);
System.out.println("After invoking removeAll() method: "+set);
//Removing elements on the basis of specified condition
set.removeIf(str->str.contains("Vijay"));
System.out.println("After invoking removeIf() method: "+set);
//Removing all the elements available in the set
set.clear();
System.out.println("After invoking clear() method: "+set);
}
}

Java Map Interface

  1. Map contains values on the basis of key i.e. Key Values and Pairs collectively known as entries.
  2. Map contains unique keys.
  3. Useful when you need to search, update and delete operations on the basis of keys.

Java Map Hierarchy

  1. There are two interfaces to implement Map in Java- Map and SortedMap and three classes- HashMap, LinkedHashMap and TreeMap.
  2. A Map cannot have duplicate keys, but can have duplicate values.
  3. HashMap and LinkedHashMap allow null keys and values.
  4. TreeMap does not allow Null keys or values.
  5. A Map cannot be traversed. Due to this, you need to convert it into a Set using keySet() or entrySet() method.

HashMap- is the implementation of the Map. Does Not maintain any order.

LinkedHashMap- Maintains insertion Order.

TreeMap- Implementation on TreeMap and SortedMap. Maintains ascending order.

Methods of Map Interface

V put(Object key, Object value)- It is used to add entries in Map.

void putAll(Map map)- Used to insert specified map into another map.

V putIfAbsent(K key, V value)- Inserts specified value at a Particular key mentioned if a value does not exist already.

V remove(Object key)- Used to delete an entry for the specified key.

Set keySet()- Returns Set view containing all the keys.

Set<Map.Entry<K,V>> entrySet()- Returns Set view containing all key values and pairs.

void clear()- Used to reset/clear the map.

boolean containsValue(Object value)- Used to check whether specified value is present in the map. If present it returns true, else returns false.

boolean containsKey(Object key)- Used to check whether specified key is present in the map. If present it returns true, else returns false.

boolean equals(Object o)- Used to compare the specified Object with the Map.

void forEach(BiConsumer<? super K,? super V> action)- Performs given action for each entry in the Map until all entries have been processed or the action throws an exception.

V get(Object key)- Returns the object that contains the value associated with the key.

int hashCode()- Return hash code value for the Map.

boolean isEmpty()- This method would return true if the Map is empty and false if it contains at least one key.

V replace(K key, V value)- Replaces specified value for a specified Key.

boolean replace(K key, V oldValue, V newValue)- Replaces the old value with the new value for a specified key.

Collection values()- It returns a collection view of the values contained in the map.

int size()- Returns the number of entries in the Map.

Methods of Map, Entry Interface

K getKey()- Obtain a key.

V getValue()- Obtain Value.

int HashCode()- Obtain hashCode.

V setValue(V value)- Used to replace corresponding value with specified value.

boolean equals(Object o)- Used to compare specified objects with other existing objects.

Example:

//Non-generic
import java.util.*;
public class MapExample1 {
public static void main(String[] args) {
Map map=new HashMap();
//Adding elements to map
map.put(1,"Amit");
map.put(5,"Rahul");
map.put(2,"Jai");
map.put(6,"Amit");
//Traversing Map
Set set=map.entrySet();//Converting to Set so that we can traverse
Iterator itr=set.iterator();
while(itr.hasNext()){
//Converting to Map.Entry so that we can get key and value separately
Map.Entry entry=(Map.Entry)itr.next();
System.out.println(entry.getKey()+" "+entry.getValue());
}
}
}
Output:
1 Amit
2 Jai
5 Rahul
6 Amit

Methods in Java

  1. Methods are a collection of instructions to perform a task.
  2. Provide code reusability.
  3. We write a method once and reuse it multiple times.
  4. Provides the developer freedom to add or remove code as per need.
  5. Improves code readability.
  6. main() method is one of the most important methods in Java

Method Declaration

Method declaration gives a brief idea about method attributes such as visibility, return-type, name and arguments.

Syntax-

public int sum (int a, int b)
{
//Method body
}

Method Signature: It includes the method name and parameter list.

Access Specifier:

  1. Represents access type of the method.
  2. Specifies visibility of the Method.

Types of Access Specifier-

  1. Public- Accessible by all classes
  2. Private- Accessible only in the same class where it is defined.
  3. Protected- Accessible only in the same package or subclasses in a different package.
  4. Default- When the access specifier is not defined in the method, Java uses Default access by default. Visible only within the same package.

Return type- It is the data type that would be returned by the method. If the method does not return anything, use void.

Method Name- Unique name provided to the method.

Parameter List- Contains data type and variable name.

Method Body- contains the action to be performed.

Types of Methods

  1. Predefined Methods
  2. User-defined Methods

Predefined Methods- Methods that are already defined in the Java Class Libraries and ready to use.

Eg- length(), equals(), compareTo(), sqrt()

Example-

MaxNum.java

public class MaxNum
{
public static void main(String[] args)
{
// using the max() method of Math class
System.out.print("Maximum number is: " + Math.max(9,7));
}
}
Output-
Maximum number is: 9

In the above example we used predefined methods like main(), max(), print(). We used them directly because they are predefined. Below are methods and classes which they belong to-

print()- PrintStream Class

max()- Math Class

User-defined method- Method defined by the programmer for promoting reusability. Support modification as they are defined by the programmer.

Example to define a method-

public int findEvenOdd(int num)
{
//Method body
if(num%2==0)
System.out.print(num+ "Number is even");
else
System.out.print(num+ "Number is odd");
}
Example to call a method-
import java.util.Scanner;
public class EvenOdd
{
Public static void main(String args[])
{
Scanner scan= new Scanner(System.in);
System.out.println("Enter the Number");
int num=scan.nextInt();
//method
findEvenOdd(num);
}
}
Output 1:
Enter the number: 7
7 Number is odd
Output 2:
Enter the number: 10
10 Number is even

Static Method

  1. A method that belongs to a class rather than instance of a class is called as static method.
  2. In short, A method that does not return a dynamic result is called as Static method.

Example:

public class Display
{
Public static void main(String args[])
{
show();
}
static void show()
{
System.out.println("Example for Static method");
}
}
Output:
Example for Static method

Instance Method

  1. Method of the class is known as an instance method.
  2. Non-static method.
  3. Before calling or invoking the instance method, it is necessary to create an object of its class.

Example:

public class InstanceMethodExample
{
public static void main(String [] args)
{
//Creating an object of the class
InstanceMethodExample obj = new InstanceMethodExample();
//invoking instance method
System.out.println("The sum is: "+obj.add(12, 13));
}
int s;
//user-defined method because we have not used static keyword
public int add(int a, int b)
{
s = a+b;
//returning the sum
return s;
}
}
Output:
The sum is: 25

There are two types of instance method:

  1. Accessor Method
  2. Mutator Method

Accessor Method: The method(s) that reads the instance variable(s) is known as the accessor method. We can easily identify it because the method is prefixed with the word get. It is also known as getters. It returns the value of the private field. It is used to get the value of the private field.

Example-

public int getId()
{
return Id;
}

Mutator Method: The method(s) read the instance variable(s) and also modify the values. We can easily identify it because the method is prefixed with the word set. It is also known as setters or modifiers. It does not return anything. It accepts a parameter of the same data type that depends on the field. It is used to set the value of the private field.

Example

public void setRoll(int roll)
{
this.roll = roll;
}

Abstract Method

  1. Methods that do not have a method body can be known as an abstract method.
  2. Method without an implementation can be called an abstract method.
  3. Class has to be abstract so that it can accommodate an abstract method.

Syntax-

abstract void method_name();

Example-

abstract class Demo //abstract class
{
//abstract method declaration
abstract void display();
}
public class MyClass extends Demo
{
//method implementation
void display()
{
System.out.println("Abstract method…");
}
public static void main(String args[])
{
//creating object of abstract class
Demo obj = new MyClass();
//invoking abstract method
obj.display();
}
}
Output:
Abstract method…

Factory Method

  1. Method that returns object to the class where it belonged.
  2. All static methods are factory methods.
  3. Eg-
NumberFormat obj = NumberFormat.getNumberInstance();

References-

  1. JavaTpoint

--

--