Download as pdf or txt
Download as pdf or txt
You are on page 1of 12

Chapter

8 COLLECTION

Collection is a group of object. Collection is like containers that group multiple items
in a single unit. List, Set and Map are the popular interfaces.
Java Collection framework can achieve all the operations that you perform on a data
such as searching, sorting, insertion, manipulation, and deletion.

Java Collections framework has following benefits:


1. Reduced Development Effort
It comes with almost all common types of collections and useful methods to iterate
and manipulate the data. So we can concentrate more on business logic rather than
designing our collection APIs.

2. Increased Quality
Using core collection classes that are well tested increases our program quality rather
than using any home developed data structure.

3. Reusability

4. Interoperability

Collection Interface
This is the root of the collection hierarchy. A collection represents a group of objects
known as its elements. The Java platform doesn’t provide any direct implementations of this
interface.
The interface has methods to tell you how many elements are in the collection (size(),
isEmpty() ), to check whether a given object is in the collection (contains() ), to add and
remove an element from the collection (add (), remove() ), and to provide an iterator over the
collection (iterator()).
Collection interface also provides bulk operations methods that work on entire
collection – containsAll(), addAll(), removeAll(), retainAll(), clear().
The toArray() methods are provided as a bridge between collections and older APIs
that expect arrays on input.

Iterator Interface
Iterator interface provides methods to iterate over any Collection. We can get iterator
instance from a Collection using iterator method. Iterator takes the place of Enumeration in

FULL STACK JAVA DEVELOPER 1


the Java Collections Framework. Iterators allow the caller to remove elements from the
underlying collection during the iteration. Iterators in collection classes implement Iterator
Design Pattern.

List Interface
List is an insertion ordered collection and can contain duplicate elements. You can access
any element from its index. List is more like array with dynamic length. List is one of the
most used Collection type. ArrayList and LinkedList are implementation classes of List
interface.

1. Array List
Java ArrayList is the resizable array implementation of List interface that means it
starts with default size and grows automatically when more data is added into array
list.
Some important points about Java ArrayList are:
 Java ArrayList is almost similar to Vector except that it’s unsynchronized, so
performance is better in single threaded environment.
 Java ArrayList is not thread safe, so special care must be given when used in
multithreaded environment.
 Java ArrayList can contain duplicate values.
 It also allows “null” value.
 Objects in java ArrayList are added in insertion order.
 Java ArrayList provides random access to its elements because it works on
index. We can retrieve any element through its index.

package com.csi.collectionconcept;
import java.util.ArrayList;
import java.util.Iterator;
public class ArrayListConcept {
public static void main(String[] args) {
ArrayList<String> al = new ArrayList<>();
al.add("IT");
al.add("COMP");
al.add("MECHANICAL");
al.add("CIVIL");
al.add("PRODUCTION");
al.add("CHEMICAL");
al.add("PETROLIUM");
al.add("IT");
al.add("ELECTRONICS");
Iterator<String> itr = al.iterator();

FULL STACK JAVA DEVELOPER 2


while (itr.hasNext()) {
System.out.println(itr.next());
}
}
}

Output:
COMP
MECHANICAL
CIVIL
PRODUCTION
CHEMICAL
PETROLIUM
IT
ELECTRONICS

2. Linked List
Java LinkedList is an implementation of the List and Deque interfaces.
It extends AbstractSequentialList and implements List and Deque interfaces.
Some important points about Java LinkedList are:
 It supports adding null elements.
 We can add any number of null elements.
 It stores elements in Insertion order.
 Internally, it is an implemented using Doubly Linked List Data Structure.
 It supports duplicate elements.
 It stores or maintains its elements in Insertion order.
 It is not synchronized that means it is not thread safe.
 We can create a synchronized LinkedList using Collections.synchronizedList()
method.
 It does not implement RandomAccess interface. So we can access elements in
sequential order only. It does not support accessing elements randomly.
 When we try to access an element from a LinkedList, searching that element
starts from the beginning or end of the LinkedList based on where that elements
is available.
 We can use ListIterator to iterate LinkedList elements.

package com.csi.collectionconcept;
import java.util.Iterator;
import java.util.LinkedList;
public class LinkedListConcept {
public static void main(String[] args) {
LinkedList<String> ll = new LinkedList<>();

FULL STACK JAVA DEVELOPER 3


ll.add("IT");
ll.add("COMP");
ll.add("MECHANICAL");
ll.add("CIVIL");
ll.add("PRODUCTION");
ll.add("CHEMICAL");
ll.add("PETROLIUM");
ll.add("IT");
ll.add("ELECTRONICS");
Iterator<String> itr = ll.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
}
}

Output:
IT
COMP
MECHANICAL
CIVIL
PRODUCTION
CHEMICAL
PETROLIUM
IT
ELECTRONICS

Set Interface
Java Set is a collection of elements (Or objects) that contains no duplicate elements. Java
Set is an interface that extends Collection interface. Set allows you to add at most one null
element only.

1. Hash Set
HashSet doesn’t allow duplicate entries.
HashSet allows null as a value.
HashSet doesn’t guarantee the insertion order of elements.
HashSet is not thread-safe.Java ArrayList is almost similar to Vector except that it’s
unsynchronized, so performance is better in single threaded environment

FULL STACK JAVA DEVELOPER 4


package com.csi.collectionconcept;
import java.util.HashSet;
import java.util.Iterator;
public class HashSetConcept {
public static void main(String[] args) {
HashSet<String> hs = new HashSet<>();
hs.add("IT");
hs.add("COMP");
hs.add("MECHANICAL");
hs.add("CIVIL");
hs.add("PRODUCTION");
hs.add("CHEMICAL");
hs.add("PETROLIUM");
hs.add("IT");
hs.add("ELECTRONICS");
Iterator<String> itr = hs.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
}
}

Output:
COMP
CIVIL
PETROLIUM
IT
ELECTRONICS
MECHANICAL
PRODUCTION
CHEMICAL

2. Tree Set
TreeSet doesn’t allow duplicate entries.
TreeSet does not allow null.
TreeSet maintains sorting order.
TreeSet is not thread-safe.

package com.csi.collectionconcept;
import java.util.Iterator;
import java.util.TreeSet;
public class TreeSetConcept {
public static void main(String[] args) {

FULL STACK JAVA DEVELOPER 5


TreeSet<String> ts = new TreeSet<>();
ts.add("IT");
ts.add("COMP");
ts.add("MECHANICAL");
ts.add("CIVIL");
ts.add("PRODUCTION");
ts.add("CHEMICAL");
ts.add("PETROLIUM");
ts.add("IT");
ts.add("ELECTRONICS");
Iterator<String> itr = ts.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
}
}

Output:
CHEMICAL
CIVIL
COMP
ELECTRONICS
IT
MECHANICAL
PETROLIUM
PRODUCTION

Map Interface
Java Map is part of collections framework. Java Map object is used to store key-value
mappings. Java Map can’t contain duplicate keys however duplicate values are allowed.
1. Hash Map
Java HashMap allows single null key and null values.
HashMap is not an ordered collection. You can iterate over HashMap entries through
keys set but they are not guaranteed to be in the order of their addition to the
HashMap.
HashMap is almost similar to Hashtable except that it’s unsynchronized and allows
null key and values.
HashMap uses it’s inner class Node<K,V> for storing map entries.
HashMap stores entries into multiple singly linked lists, called buckets or bins.
Default number of bins is 16 and it’s always power of 2.

FULL STACK JAVA DEVELOPER 6


HashMap uses hashCode() and equals() methods on keys for get and put operations.
So HashMap key object should provide good implementation of these methods. This
is the reason immutable classes are better suitable for keys, for example String and
Integer.

package com.csi.collectionconcept;
import java.util.HashMap;
import java.util.Map;
public class HashMapConcept {
public static void main(String[] args) {
HashMap<String, String> hm = new HashMap<>();
hm.put("ID", "121");
hm.put("NAME", "JERRY");
hm.put("SALARY", "96000.99");
hm.put("ADDRESS", "PUNE");
for (Map.Entry<String, String> m : hm.entrySet()) {
System.out.println(m.getKey() + ": " + m.getValue());
}
}
}

Output:
SALARY: 96000.99
ADDRESS: PUNE
ID: 121
NAME: JERRY

2. Tree Map
Java TreeMap contains only unique elements.
Java TreeMap cannot have a null key but can have multiple null values.
Java TreeMap is non-synchronized.
Java TreeMap maintains ascending order.

package com.csi.collectionconcept;
import java.util.Map;
import java.util.TreeMap;
public class TreeMapConcept {
public static void main(String[] args) {
TreeMap<String, String> tm = new TreeMap<>();
tm.put("ID", "121");
tm.put("NAME", "JERRY");
tm.put("SALARY", "96000.99");

FULL STACK JAVA DEVELOPER 7


tm.put("ADDRESS", "PUNE");
for (Map.Entry<String, String> m : tm.entrySet()) {
System.out.println(m.getKey() + ": " + m.getValue());
}
}
}

Output:
ADDRESS: PUNE
ID: 121
NAME: JERRY
SALARY: 96000.99

How to compare object with String?


Contains Method
Java String contains() method was introduced in java 1.5 release as a utility method.
This method returns true if the string contains the specified sequence of char values.
Else it returns false.
Note that string contains() method is case sensitive, so "credit".contains("C"); will
return false.
The argument of String contains() method is java.lang.CharSequence, so any
implementation classes are also fine as argument, such as StringBuffer, StringBuilder
and CharBuffer.
For case insensitive check, we can change both the strings to either upper case or lower
case before calling the contents() method.

package com.csi.collectionconcept;
import java.util.ArrayList;
import java.util.Scanner;
public class ContainsMethodConcept {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter Product Name to check availability: ");
String productName = sc.next();
ArrayList<String> productList = new ArrayList<>();
productList.add("MI");
productList.add("LENOVO");
productList.add("DELL");
productList.add("APPLE");

FULL STACK JAVA DEVELOPER 8


productList.add("HP");
if (productList.contains(productName)) {
System.out.println("Product is available");
} else {
System.out.println("Product is not available");
}

}
}

Output:
Please enter Product Name to check availability:
MI
Product is available

Comparable Interface
Comparable is used for single sequence sorting. It is available in java.lang package. By
default compareTo method available in Comparator.
Java provides Comparable interface which should be implemented by any custom class
if we want to use Arrays or Collections sorting methods.
The Comparable interface has compareTo(T obj) method which is used by sorting
methods, you can check any Wrapper, String or Date class to confirm this. We should
override this method in such a way that it returns a negative integer, zero, or a positive
integer if “this” object is less than, equal to, or greater than the object passed as an
argument.
After implementing Comparable interface in Employee class, here is the resulting
Employee class.

package com.csi.collectionconcept;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
class Employee implements Comparable<Employee> {
int empId;
String empName;
int empAge;
public Employee(int empId, String empName, int empAge) {
super();
this.empId = empId;
this.empName = empName;
FULL STACK JAVA DEVELOPER 9
this.empAge = empAge;
}
public String toString() {
return "Employee [empId=" + empId + ", empName=" + empName + ",
empAge=" + empAge + "]";
}
public int compareTo(Employee e1) {
if (empAge == e1.empAge) {
return 0;
} else if (empAge > e1.empAge) {
return 1;
} else {
return -1;
}
}
}
public class ComparableConcept {
public static void main(String[] args) {
List<Employee> employeeList = new ArrayList<>();
employeeList.add(new Employee(121, "JERRY", 21));
employeeList.add(new Employee(122, "TOM", 24));
employeeList.add(new Employee(120, "RABEA", 20));
Collections.sort(employeeList);
employeeList.forEach(emp -> System.out.println(emp));
}
}

Output
Sort By Name
Customer [customerId=129, customerName=JERRY, customerAge=25]
Customer [customerId=145, customerName=RABEA, customerAge=20]
Customer [customerId=126, customerName=TOM, customerAge=23]
Sort By Age
Customer [customerId=145, customerName=RABEA, customerAge=20]
Customer [customerId=126, customerName=TOM, customerAge=23]
Customer [customerId=129, customerName=JERRY, customerAge=25]

Comparator Interface
Comparator is used to multiple sequence sorting. It is available in java.util package. In
comparator two methods available- compare() and equals().
Comparator interface compare(Object o1, Object o2) method need to be implemented
that takes two Object argument, it should be implemented in such a way that it returns

FULL STACK JAVA DEVELOPER 10


negative int if the first argument is less than the second one and returns zero if they are
equal and positive int if the first argument is greater than the second one.

package com.csi.collectionconcept;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
class Customer {
int customerId;
String customerName;
int customerAge;
public Customer(int customerId, String customerName, int customerAge) {
super();
this.customerId = customerId;
this.customerName = customerName;
this.customerAge = customerAge;
}
public String toString() {
return "Customer [customerId=" + customerId + ", customerName=" +
customerName + ", customerAge=" + customerAge
+ "]";
}
}
class SortByName implements Comparator<Customer> {
public int compare(Customer c1, Customer c2) {
return c1.customerName.compareTo(c2.customerName);
}
}
class SortByAge implements Comparator<Customer> {
public int compare(Customer c1, Customer c2) {
if (c1.customerAge == c2.customerAge) {
return 0;
} else if (c1.customerAge > c2.customerAge) {
return 1;
} else {
return -1;
}
}
}
public class ComparatorConcept {
public static void main(String[] args) {
List<Customer> customerList = new ArrayList<>();
customerList.add(new Customer(126, "TOM", 23));
customerList.add(new Customer(129, "JERRY", 25));
customerList.add(new Customer(145, "RABEA", 20));
System.out.println("Sort By Name");
FULL STACK JAVA DEVELOPER 11
Collections.sort(customerList, new SortByName());
customerList.forEach(custname -> System.out.println(custname));
System.out.println("Sort By Age");
Collections.sort(customerList, new SortByAge());
customerList.forEach(custage -> System.out.println(custage));
}
}

Output:
Sort By Name
Customer [customerId=129, customerName=JERRY, customerAge=25]
Customer [customerId=145, customerName=RABEA, customerAge=20]
Customer [customerId=126, customerName=TOM, customerAge=23]
Sort By Age
Customer [customerId=145, customerName=RABEA, customerAge=20]
Customer [customerId=126, customerName=TOM, customerAge=23]
Customer [customerId=129, customerName=JERRY, customerAge=25]

FULL STACK JAVA DEVELOPER 12

You might also like