Sunday, January 9, 2022

Java — Collection introduction

 Why to go for Collection?

  • Java Collections Framework provides lots of different useful data types, such as linked lists (allows insertion anywhere in constant time), resizeable array lists (like Vector but cooler), red-black trees, hash-based maps (like Hashtable but cooler).
  • Java Collections Framework provides abstractions, so you can refer to a list as a List, whether backed by an array list or a linked list; and you can refer to a map/dictionary as a Map, whether backed by a red-black tree or a hashtable.
  • Collection framework is used with various operations and having various in-build methods. They are as follows:
  • As collection framework is growable in nature some need not worry about the size.
  • Collection framework can hold both homogeneous and heterogeneous objects.
  • Collection framework is implemented based on some standard data structure. Hence, ready-made methods are available to use as per the requirement.

Any group of individual objects which are represented as a single unit is known as the collection of the objects. In Java, a separate framework named the “Collection Framework” has been defined in JDK 1.2 which basically holds all the collection classes and interface in it.

What is a Framework?

A framework is a set of classes and interfaces which provide a ready-made architecture. In order to implement a new feature or a class, there is no need to define a framework.

Note: Collection interface (java.util.Collection) and Map interface (java.util.Map) are the two main “root” interfaces of Java collection classes.

Collection Framework Hierarchy

Java Collections Interface Methods

The table below describes the methods available to use against Java Collections for data Manipulation Jobs.

Collections In java and How to Implement Them?

Set Interface

The set interface is inherited from the Java collections Interface A Set interface cannot store duplicate/redundant elements in it. Here’s an example based on a set interface.

Example:

//Set Interface

package Simplilearn;

import java.util.*;

public class SetExample {

public static void main(String args[]) {

int count[] = { 21, 23, 43, 53, 22, 65 };

Set<Integer> set = new HashSet<Integer>();

try {

for (int i = 0; i <= 5; i++) {

set.add(count[i]);

}

System.out.println(set);

TreeSet<Integer> sortedSet = new TreeSet<Integer>(set);

System.out.println(“The sorted list is:”);

System.out.println(sortedSet);

System.out.println(“First element of the set is: “ + (Integer) sortedSet.first());

System.out.println(“last element of the set is: “ + (Integer) sortedSet.last());

} catch (Exception e) {

}

}

}

List Interface

The List interface is derived from the java util package. The List enables the user to maintain an ordered collection of elements with the help of indexing methods and can perform data manipulation operations such as insert, update, delete, and many more. For instance:

Example:

//List Interface

package Simplilearn;

import java.util.*;

public class ListInterface {

public static void main(String args[]) {

List<String> list = new ArrayList<String>();

list.add(“David”);

list.add(“Jhon”);

list.add(“Stacy”);

//list.add(“Stacy”);

for (String Students : list)

System.out.println(Students);

}

}

Queue Interface

A Queue interface is inherited from the Java Collections interface. The Queue is a linear Collection that offers data manipulation operations on the collection elements, and follows the FIFO(First In First Out) principle. For example:

Example:

//Queue Interface

package Simplilearn;

import java.util.*;

public class QueueInterface {

public static void main(String[] args) {

Queue<String> queue = new LinkedList<>();

queue.add(“Apple”);

queue.add(“Mango”);

queue.add(“Grapes”);

queue.add(“Banana”);

System.out.println(queue);

queue.remove(“Grapes”);

System.out.println(queue);

System.out.println(“Queue total Size: “ + queue.size());

System.out.println(“Queue includes fruit ‘Apple’? : “ + queue.contains(“Apple”));

queue.clear();

}

}

Deque Interface

A Deque interface is inherited from the Java Collections Interface. The term DE-Que stands for Double-Ended Queue. The Deque supports insertion and deletion operations on both sides of the Queue.

Example:

//Deque Interface

package Simplilearn;

import java.util.ArrayDeque;

import java.util.Deque;

public class DequeInterface {

public static void main(String[] args) {

Deque<Integer> num = new ArrayDeque<>();

num.offer(10);

num.offerLast(21);

num.offerFirst(52);

System.out.println(“Deque elements: “ + num);

int first = num.peekFirst();

System.out.println(“First Element is: “ + first);

int lastElement = num.peekLast();

System.out.println(“Last Element: “ + lastElement);

int removed = num.pollFirst();

System.out.println(“Removed First Element: “ + removed);

System.out.println(“Updated Deque is: “ + num);

}

}

Map Interface

The Map interface is inherited from Java Collection Interface. The Map cannot store duplicate elements. A Map stores data using the key-value pair format. The manipulation operations are taken care of through accessing the key-value pairs.

Next up: an example based on the Map interface

Example:

//Map Interface

package Simplilearn;

import java.util.*;

import java.util.Map.Entry;

public class MapInterface {

public static void main(String args[]) {

Map<Integer, String> map = new HashMap<Integer, String>();

map.put(1, “Cricket”);

map.put(2, “Hockey”);

map.put(3, “Archery”);

for (Iterator<Entry<Integer, String>> iterator = map.entrySet().iterator(); iterator.hasNext();) {

Entry<Integer, String> m = iterator.next();

System.out.println(m.getKey() + “ “ + m.getValue());

}

}

}

SortedSet Interface

Sorted set interface maintains mapping in ascending order. They are used for naturally ordered collection.

An example of SortedSet Interface:

//Sortedset Interface

package Simplilearn;

import java.util.*;

public class SortedSetInterface {

public static void main(String[] args) {

SortedSet set = new TreeSet();

set.add(“Bob”);

set.add(“Sean”);

set.add(“Jennifer”);

Iterator i = set.iterator();

while (i.hasNext()) {

Object element = i.next();

System.out.println(element.toString());

}

}

}

SortedMap Interface

A Sorted map interface maintains the mappings of elements in ascending critical order. SortedMap is the Map analog of SortedSet.

Example:

//Sortedmap Interface

package Simplilearn;

import java.util.*;

public class SortedMapInterface {

public static void main(String args[]) {

TreeMap<String, Double> t = new TreeMap<String, Double>();

t.put(“John”, new Double(76.5));

t.put(“Molley”, new Double(87.3));

t.put(“Aron”, new Double(78.2));

t.put(“Daisy”, new Double(73.4));

Set<?> set = t.entrySet();

Iterator<?> i = set.iterator();

while(i.hasNext()) {

@SuppressWarnings(“rawtypes”)

Map.Entry me = (Map.Entry)i.next();

System.out.print(me.getKey() + “: “);

System.out.println(me.getValue());

}

System.out.println();

double percentage = ((Double)t.get(“Molley”)).doubleValue();

t.put(“Molley”, new Double(percentage));

System.out.println(“Zara’s new balance: “ + t.get(“Molley”));

}

}

Java Collection Classes

HashSet Class

The HashSet class is inherited from the AbstractSet class. HashSet class stores the elements using a Hash table.HashSet allows null elements and does not follow any order to store the elements.

Here’s an example of HashSet:

//HashSet Class

package Simplilearn;

import java.util.HashSet;

public class HashSetClass {

public static void main(String args[]) {

HashSet<String> hset = new HashSet<String>();

hset.add(“Suzuki”);

hset.add(“Kawasaki”);

hset.add(“Honda”);

hset.add(“Ducati”);

hset.add(“Yamaha”);

hset.add(“Yamaha”);

hset.add(“Suzuki”);

hset.add(null);

hset.add(null);

// Displaying HashSet elements

System.out.println(hset);

}

}

TreeSet Class

TreeSet Class is a NavigableSet implementation based on TreeMap. Here, the elements are ordered using comparators.

Let us check an example based on TreeSet Class.

//TreeSet

package Simplilearn;

import java.util.TreeSet;

public class TreeSetClass {

public static void main(String args[]) {

TreeSet<Integer> treeset = new TreeSet<Integer>();

treeset.add(8476);

treeset.add(748);

treeset.add(88);

treeset.add(983);

treeset.add(18);

treeset.add(0);

System.out.println(treeset);

}

}

ArrayList Class

ArrayList in java is a resizable array that is an implementation of ListInterface that allows null elements. The ArrayList has three different types of Arrays, as shown below.

  • One Dimensional Array
  • Two Dimensional Array
  • Multidimensional Array

One Dimensional Array

One Dimensional Array has one row that arranges the elements in the sequential order of addresses, as shown in the image below.

Here’s an example of One Dimensional Array:

//One-Dimensional Array

package Simplilearn;

public class OneDA {

public static void main(String args[]) {

int[] a = new int[3];

a[0] = 10;

a[1] = 20;

a[2] = 30;

System.out.println(“One dimensional array”);

System.out.println(a[0]);

System.out.println(a[1]);

System.out.println(a[2]);

}

}

Two Dimensional Array

Two Dimensional Array has rows and columns. It arranges the elements in the form of a matrix, as shown in the image below.

For a better understanding of Two Dimensional Array, let us go through the example.

Example:

//Two-Dimensional Array

package Simplilearn;

public class TwoDA {

public static void main(String[] args) {

int[][] arr = { { 1, 2 }, { 3, 4 } };

for (int i = 0; i < 2; i++)

for (int j = 0; j < 2; j++)

System.out.println(“arr[“ + i + “][“ + j + “] = “ + arr[i][j]);

}

}

Multidimensional Array

The Multidimensional Array is a combination of multiple two-dimensional arrays; it looks like a 3-D image as shown below

To understand in a better way, let us check out an example of a Multidimensional Array.

Example:

//Three/Multi-Dimensional Array

package Simplilearn;

public class ThreeDA {

public static void main(String args[]) {

int A[][] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };

for (int i = 0; i < 3; i++) {

for (int j = 0; j < 3; j++) {

System.out.print(A[i][j] + “ “);

}

System.out.println();

}

}

}

LinkedList Class

LinkedList class is an implementation of a list and deque interfaces. Linked List is similar to an array, but it does not store data in sequential data addresses, but connects the memory blocks in the sequential order and allows null elements.

There are three different types of linked lists.

  • Singly Linked List
  • Doubly Linked List
  • Circular Linked List

Singly Linked List

A Singly Linked List stores elements in different memory locations and then connects them in one direction to represent them sequentially. A typical singly-linked List is shown in the image below.

A Singly linked list offers traversal in one direction only.

To understand a singly linked list in a better way, here’s an example:

//Singly-LinkedList

package Simplilearn;

public class SiinglyLinkedList {

Node head;

static class Node {

int data;

Node next;

Node(int d) {

data = d;

next = null;

}

}

public void display() {

Node n = head;

while (n != null) {

System.out.print(n.data + “ “);

n = n.next;

}

}

public static void main(String[] args) {

SiinglyLinkedList list = new SiinglyLinkedList();

list.head = new Node(1);

Node second = new Node(2);

Node third = new Node(3);

Node fourth = new Node(4);

list.head.next = second;

second.next = third;

third.next = fourth;

list.display();

}

}

Doubly Linked List

A Doubly linked list is typically a Singly linked list, but a doubly linked list offers traversal in two directions. Here’s how a typical doubly linked list looks like:

To understand a doubly linked list in a better way, let us check an example.

Example:

//Doubly LinkedList

package Simplilearn;

public class DoublyLinkedList {

class Node {

int data;

Node previous;

Node next;

public Node(int data) {

this.data = data;

}

}

Node head, tail = null;

public void addNode(int data) {

Node newNode = new Node(data);

if (head == null) {

head = tail = newNode;

head.previous = null;

tail.next = null;

} else {

tail.next = newNode;

newNode.previous = tail;

tail = newNode;

tail.next = null;

}

}

public void display() {

Node current = head;

if (head == null) {

System.out.println(“List is empty”);

return;

}

System.out.println(“Nodes of doubly linked list: “);

while (current != null) {

System.out.print(current.data + “ “);

current = current.next;

}

}

public static void main(String[] args) {

DoublyLinkedList dList = new DoublyLinkedList();

dList.addNode(1);

dList.addNode(2);

dList.addNode(3);

dList.addNode(4);

dList.addNode(5);

dList.display();

}

}

Circular Linked List

A circular linked list is a typical singly linked list. The only change is that the Circular linked List’s end/tail points back to the linked List’s head node. The Head and Tail Connection at the end makes the circular linked List to offer circular traversal.

To understand a Circular linked list in a better way, let us check an example

Example:

//Circular LinkedList

package Simplilearn;

public class CLL {

public class Node{

int data;

Node next;

public Node(int data) {

this.data = data;

}

}

public Node head = null;

public Node tail = null;

public void add(int data){

Node newNode = new Node(data);

if(head == null) {

head = newNode;

tail = newNode;

newNode.next = head;

}

else {

tail.next = newNode;

tail = newNode;

tail.next = head;

}

}

public void display() {

Node current = head;

if(head == null) {

System.out.println(“List is empty”);

}

else {

System.out.println(“Nodes of the circular linked list: “);

do{

System.out.print(“ “+ current.data);

current = current.next;

}while(current != head);

System.out.println();

}

}

public static void main(String[] args) {

CLL c = new CLL();

c.add(1);

c.add(2);

c.add(3);

c.add(4);

c.add(5);

c.add(6);

c.add(7);

c.add(8);

c.display();

}

}

HashMap Class

HashMap is derived from the Map interface. HashMap stores data using the key-value pair method. HashMap does not allow duplicate elements.

Here’s an example based on HashMap:

//HashMap Class

package Simplilearn;

import java.util.HashMap;

public class HashMapClass {

public static void main(String[] args) {

HashMap<String, String> Make = new HashMap<String, String>();

Make.put(“Honda”, “CBR”);

Make.put(“Kawasaki”, “Ninja”);

Make.put(“Ducati”, “Panigale”);

Make.put(“Yamaha”, “R1”);

System.out.println(Make);

}

}

TreeMap Class

The TreeMap is derived from the AbstractMap Class. TreeMap stores elements in the form of key-value pairs. TreeMap does not allow null and duplicate values in the collection.

Let us go through an example based on TreeMap.

Example:

//TreeMap Class

package Simplilearn;

import java.util.*;

import java.util.Map.Entry;

public class TreeMapClass{

public static void main(String args[]){

TreeMap<Integer,String> map=new TreeMap<Integer,String>();

map.put(2019901,”Amber”);

map.put(2019902,”james”);

map.put(2019903,”Violet”);

map.put(2019904,”Reynolds”);

for (Iterator<Entry<Integer, String>> iterator = map.entrySet().iterator(); iterator.hasNext();) {

Entry<Integer, String> m = iterator.next();

System.out.println(m.getKey()+” “+m.getValue());

}

}

}

Followed by the Java Collections Classes, we will now enter into the last adjacent branch of Java Collections, the Java Collection Algorithm APIs.

Collection API Algorithms

Java Collection API algorithms provide implementations that are commonly used in searching, sorting and other jobs.

Sorting

The sorting Algorithm is one of the Collections API Algorithms. The sorting Algorithm does the job of ordering the elements in an ascending or descending order based on the modifications written by the user.

To understand the sorting Algorithm in a better way here’s an example

Example:

//Bubble Sort

package Simplilearn;

public class BubbleSort {

static void bubbleSort(int[] arr) {

int n = arr.length;

int temp = 0;

for (int i = 0; i < n; i++) {

for (int j = 1; j < (n — i); j++) {

if (arr[j — 1] > arr[j]) {

temp = arr[j — 1];

arr[j — 1] = arr[j];

arr[j] = temp;

}

}

}

}

public static void main(String[] args) {

int arr[] = { 289, 39, 48, 6, 28, 1, 2, 33 };

System.out.println(“Array Before Bubble Sort”);

for (int j = 0; j < arr.length; j++) {

System.out.print(arr[j] + “ “);

}

System.out.println();

bubbleSort(arr);

System.out.println(“Array After Bubble Sort”);

for (int j = 0; j < arr.length; j++) {

System.out.print(arr[j] + “ “);

}

}

}

Shuffling

The shuffling Algorithm is one of the Collections API algorithms. The functionality of the Shuffling Algorithm is to destroy the current arrangements. They are employed on creating randomness in the List.

Let us check out an example to understand it in a better way

Example:

//Shuffle algorithm

package Simplilearn;

import java.util.Arrays;

import java.util.Collections;

import java.util.List;

public class Shuffle {

public static void main(String[] args) {

Integer[] intA = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 };

List<Integer> intL = Arrays.asList(intA);

Collections.shuffle(intL);

intL.toArray(intA);

System.out.println(Arrays.toString(intA));

}

}

Searching

A searching algorithm is employed to search an element in the list/array based on the type of searching mechanism used.

Example:

//Binary Search

package Simplilearn;

public class BinarySearch1 {

public static int binarySearch(int arr[], int first, int last, int key) {

if (last >= first) {

int mid = first + (last — first) / 2;

if (arr[mid] == key) {

return mid;

}

if (arr[mid] > key) {

return binarySearch(arr, first, mid — 1, key);

} else {

return binarySearch(arr, mid + 1, last, key);

}

}

return -1;

}

public static void main(String args[]) {

int arr[] = { 1, 2, 3, 4, 5 };

int k = 2;

int last = arr.length — 1;

int result = binarySearch(arr, 0, last, k);

if (result == -1)

System.out.println(“Element is not found!”);

else

System.out.println(“Element is found at index: “ + result);

}

}

Composition

The frequency and disjoint algorithms check a few aspects of the composition of one or more Collections.

The composition has two parts:

  1. Frequency: checks the count of an element repeated
  2. Disjoint: makes sure no element is repeated

Example:

//Composition

package Simplilearn;

import java.io.*;

import java.util.*;

class Book {

public String title;

public String author;

Book(String title, String author) {

this.title = title;

this.author = author;

}

}

class Library {

// reference to refer to list of books.

private final List<Book> books;

Library(List<Book> books) {

this.books = books;

}

public List<Book> getTotalBooksInLibrary() {

return books;

}

}

public class Composition {

public static void main(String[] args) {

Book b1 = new Book(“EffectiveJ Java”, “Joshua Bloch”);

Book b2 = new Book(“Thinking in Java”, “Bruce Eckel”);

Book b3 = new Book(“Java: The Complete Reference”, “Herbert Schildt”);

List<Book> books = new ArrayList<Book>();

books.add(b1);

books.add(b2);

books.add(b3);

Library library = new Library(books);

List<Book> bks = library.getTotalBooksInLibrary();

for (Book bk : bks) {

System.out.println(“Title : “ + bk.title + “ and “ + “ Author : “ + bk.author);

}

}

}

Benefits of Java Collections

Software/Code Reusability

Java Collections have reduced the coding lines impeccably and, along with that, featured the most reliable way code reusability.

Ease of Designing APIs

The predefined Java Collections algorithm APIs have reduced the time drastically. The absence of these APIs would have resulted in hours of coding for simple sorting operations.Simpler to Learn and Use New APIs

The use of predefined API has made the learning process more straightforward and way more useful.

Increased Speed in Programming

The simplification introduced by the Java Collections had reduced the effort on programmers. Ease of coding procedures, in turn, resulted in the most effective and efficient programming practices that save time.


No comments:

Post a Comment

JAVA 8 — Lambda Expression

  Lambda Function Anonymous function. No name. No return type. no modifiers. aqnd use ->(arroow symbol) Example: /** * @Author pankaj *...