0% found this document useful (0 votes)
2 views

Unit 4

Cfug

Uploaded by

mahimanoharn
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Unit 4

Cfug

Uploaded by

mahimanoharn
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

Dept.

of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

UNIT – IV
The Collections Framework (java.util)- Collections overview, Collection Interfaces, The Collection
classes- Array List, Linked List, Hash Set, Tree Set, Priority Queue, Array Deque. Accessing a
Collection via an Iterator, Using an Iterator, The For-Each alternative, Map Interfaces and Classes,
Comparators, Collection algorithms, Arrays, The Legacy Classes and Interfaces- Dictionary,
Hashtable ,Properties, Stack, Vector
More Utility classes, String Tokenizer, Bit Set, Date, Calendar, Random, Formatter, Scanner

A Java collection framework provides an architecture to store and manipulate a group of objects.

A Java collection framework includes the following:

Interfaces

Classes

Algorithm

Interfaces:

Interface in Java refers to the abstract data types. They allow Java collections to be manipulated
independently from the details of their representation. Also, they form a hierarchy in object-oriented
programming languages.

Classes: Classes in Java are the implementation of the collection interface. It basically refers to the data
structures that are used again and again.

Algorithm: Algorithm refers to the methods which are used to perform operations such as searching and
sorting, on objects that implement collection interfaces.

The Java collection framework provides the developers to access prepackaged data structures as well as
algorithms to manipulate data.

Collection Framework Hierarchy

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 1


Dept. of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 2


Dept. of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

Java Collection

Iterator interface :

Iterator is an interface that iterates the elements.

It is used to traverse the list and modify the elements. Iterator interface has three methods which are
mentioned below:

public boolean hasNext() – This method returns true if the iterator has more elements.

public object next() – It returns the element and moves the cursor pointer to the next element.

public void remove() – This method removes the last elements returned by the iterator.

Java Collections - List

A List is an ordered Collection of elements which may contain duplicates. It is an interface that extends
the Collection interface.

1. ArrayList

2.LinkedList

3.Vectors

Array list:

ArrayList is the implementation of List Interface where the elements can be dynamically added or
removed from the list.

Also, the size of the list is increased dynamically if the elements are added more than the initial size.

Syntax:

ArrayList object = new ArrayList ();

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 3


Dept. of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

Method Description

boolean add(Collection c) Appends the specified element to the end of a list.

void add(int index, Object


Inserts the specified element at the specified position.
element)

void clear() Removes all the elements from this list.

Return the index in this list of the last occurrence of the specified element, or -1 if
int lastIndexOf(Object o)
the list does not contain this element.

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 4


Dept. of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

Object clone() Return a shallow copy of an ArrayList.

Object[] toArray() Returns an array containing all the elements in the list.

void trimToSize() Trims the capacity of this ArrayList instance to be the list’s current size.

Example:

import java.util.*;

class DemoArrayList{

public static void main(String args[]){

ArrayList al=new ArrayList(); // creating array list

al.add("kmit"); // adding elements

al.add("Kmec");

al.add("501");

al.add("kmit");

al.set(1,"NGIT");

System.out.println(al.size());

System.out.println(al.indexOf("501"));

al.remove("kmit");

System.out.println(al.lastIndexOf("kmit"));

Iterator itr=al.iterator();

while(itr.hasNext()){

System.out.println(itr.next());

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 5


Dept. of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

Linked List

Linked List: Linked List is a sequence of links which contains items. Each link contains a connection to
another link.

Syntax: Linkedlist object = new Linkedlist();

Java Linked List class uses two types of Linked list to store the elements:

Singly Linked List

Doubly Linked List

Singly Linked List: In a singly Linked list each node in this list stores the data of
the node and a pointer or reference to the next node in the list.

Linked List Example:


import java.util.*;
public class DemoLinked{
public static void main(String args[]){
LinkedList<String> list=new LinkedList<String>();
//Adding elements to the Linked list
list.add("Sree");
list.add("Ram");
list.add("Raj");
//Adding an element to the first position
list.addFirst("KMIT");
//Adding an element to the last position
list.addLast("Sita");
//Adding an element to the 3rd position
list.add(2, "NGIT");

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 6


Dept. of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

list.removeFirst();

//Removing Last element


list.removeLast();
list.remove(1);
//Iterating LinkedList
Iterator<String> iterator=list.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}
}
}

Vector:
Vectors : Vectors are similar to arrays, where the elements of the vector object can be
accessed via an index into the vector.
Vector is synchronized.
Vector contains many legacy methods that are not part of the collections framework

Syntax:
Vector object = new Vector(size,increment);

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 7


Dept. of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

Hash Set

Java.util.HashSet class is a member of the Java collections framework which inherits


the AbstractSet class and implements the Set interface. It implicitly implements a
hashtable for creating and storing a collection of unique elements. Hashtable is
nothing but an instance of the HashMap class that uses a hashing mechanism for
storing the information within a HashSet.

Hashing is the process of converting the informational content into a unique value that
is more popularly known as hash code. This hashcode is then used for indexing the
data associated with the key. The entire process of transforming the informational key
into the hashcode is performed internally.

features:

A HashSet in Java does not allow duplicate values.


It can contain null values.
HashSet doesn’t follow the insertion order for storing the data rather it
makes use of the hashcode for indexing the values within.
It is non-synchronized which automatically makes it thread-unsafe.
HashSet class also implements Cloneable and Serializable interfaces.

HashSet Hierarchy in Java

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 8


Dept. of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

Constructors of java.util.HashSet Class


Constructor Description
HashSet () This is the default constructor of HashSet class
This constructor is used to initialize the initial capacity of
HashSet (int capacity) the hash set. The capacity can grow dynamically with the
addition of new elements
HashSet (int capacity, float This constructor is used to initialize the initial capacity of
loadCapacity) the hash set along with the load capacity
This constructor is used to initialize the hash set by using
HashSet (Collection c) the elements from Collection c

This method helps in adding a specified element into the


boolean add(Object obj)
HashSet only if it is not present
This method helps in removing all of the elements from
void clear()
HashSet
This method returns a shallow copy of the HashSet
Object clone()
instance rather than clones of the HashSet elements
This method returns true if the passed element is present
boolean contains(Object o)
within the HashSet

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 9


Dept. of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

boolean isEmpty() This method returns true in case the HashSet is empty
This method returns an iterator over the elements present
Iterator iterator()
in the HashSet
This method helps in removing the specified element from
boolean remove(Object o)
the HashSet if it is present
This method returns the total number of elements present
int size()
in the HashSet

Example:
import java.util.HashSet;
import java.util.*;

public class SampleHashSet {


public static void main(String[] args) {
// Creating a HashSet
Set<String> eduCourses = new HashSet<>();

// Adding new elements to the HashSet


eduCourses.add("Big Data");
eduCourses.add("Node.js");
eduCourses.add("Java");
eduCourses.add("Python");
eduCourses.add("Blockchain");
eduCourses.add("JavaScript");
eduCourses.add("Selenium");
eduCourses.add("AWS");
eduCourses.add("Machine Learning");
eduCourses.add("RPA");

// Adding duplicate elements will be ignored


eduCourses.add("Java");
eduCourses.add("RPA");

System.out.println(eduCourses);

// Check if the HashSet contains an specific element

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 10


Dept. of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

String myCourse = "Node.js";


if(eduCourses.contains(myCourse)) {
System.out.println(myCourse + " is in the courses list.");
} else {
System.out.println(myCourse + " is not in the courses list.");
}

// Sorting eduCourses using List


List<String> list = new ArrayList<String>(eduCourses);
Collections.sort(list);

// Printing the sorted elements of the HashSet


System.out.println("Printing the Courses in sorted order using List: " +
list);

// Removing items from HashSet using remove()


eduCourses.remove("Python");

// Iterating over HashSet items


System.out.println("Iterating over course list after removing Python:");
Iterator<String> i = eduCourses.iterator();
while (i.hasNext())
System.out.println(i.next());

// Creating another object of HashSet


HashSet<String> eduNewCourses = new HashSet<String>();
eduNewCourses.add("Node.js");
eduNewCourses.add("Python");
eduNewCourses.add("Machine Learning");

//Removing all the new elements from HashSet


eduCourses.removeAll(eduNewCourses);
System.out.println("After invoking removeAll() method courses left: "+
eduCourses);

//Removing elements on the basis of specified condition


Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 11
Dept. of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

eduCourses.removeIf(str->str.contains("Java"));
System.out.println("After invoking removeIf() method: "+
eduCourses);

// Removing elements from eduCourses which are specified in


eduNewCourses
eduCourses.retainAll(eduNewCourses);
System.out.println("HashSet after " + "retainAll() operation : " +
eduNewCourses);

//Removing all the elements available in the set


eduCourses.clear();
System.out.println("After invoking clear() method: "+ eduCourses);

}
}

Tree Set:
TreeSet is similar to HashSet except that it sorts the elements in the ascending
order while HashSet doesn’t maintain any order. TreeSet allows null element but like
HashSet it doesn’t allow. Like most of the other collection classes this class is also
not synchronized.

Example:
import java.util.TreeSet;
public class TreeSetExample {
public static void main(String args[]) {
// TreeSet of String Type
TreeSet<String> tset = new TreeSet<String>();

// Adding elements to TreeSet<String>


tset.add("ABC");
tset.add("String");
tset.add("Test");
tset.add("Pen");
tset.add("Ink");
tset.add("Jack");

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 12


Dept. of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

//Displaying TreeSet
System.out.println(tset);

// TreeSet of Integer Type


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

// Adding elements to TreeSet<Integer>


tset2.add(88);
tset2.add(7);
tset2.add(101);
tset2.add(0);
tset2.add(3);
tset2.add(222);
System.out.println(tset2);
}
}

Priority Queue
Java PriorityQueue class is a queue data structure implementation in which objects are processed
based on their priority. It is different from standard queues where FIFO (First-In-First-Out) algorithm is
followed.

In a priority queue, added objects are according to their priority. By default, the priority is determined
by objects’ natural ordering. Default priority can be overridden by a Comparator provided at queue
construction time.

PriorityQueue Features

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 13


Dept. of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

PriorityQueue is an unbounded queue and grows dynamically. The default initial capacity
is '11' which can be overridden using initialCapacity parameter in appropriate constructor.
It does not allow NULL objects.
Objects added to PriorityQueue MUST be comparable.
The objects of the priority queue are ordered by default in natural order.
A Comparator can be used for custom ordering of objects in the queue.
The head of the priority queue is the least element based on the natural ordering or
comparator based ordering. When we poll the queue, it returns the head object from the
queue.
If multiple objects are present of same priority the it can poll any one of them randomly.
PriorityQueue is not thread safe. Use PriorityBlockingQueue in concurrent environment.
It provides O(log(n)) time for add and poll methods.
2. Java PriorityQueue Example

Example:

Employee.java
public class Employee implements Comparable<Employee> {

private Long id;


private String name;
private LocalDate dob;

public Employee(Long id, String name, LocalDate dob) {


super();
this.id = id;
this.name = name;
this.dob = dob;
}

@Override
public int compareTo(Employee emp) {
return this.getId().compareTo(emp.getId());
}

//Getters and setters

@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ", dob=" + dob + "]";
}

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 14


Dept. of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

Array Deque

Interfaces implemented by ArrayDeque


The ArrayDeque class implements these two interfaces:
Java Queue Interface
Java Deque Interface

Creating ArrayDeque
In order to create an array deque, we must import the java.util.ArrayDeque
package.

Here is how we can create an array deque in Java:

ArrayDeque<Type> animal = new ArrayDeque<>();


Here, Type indicates the type of the array deque. For example,

// Creating String type ArrayDeque


ArrayDeque<String> animals = new ArrayDeque<>();

// Creating Integer type ArrayDeque


ArrayDeque<Integer> age = new ArrayDeque<>();

Insert Elements to Deque


1. Add elements using add(), addFirst() and addLast()

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 15


Dept. of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

add() - inserts the specified element at the end of the array deque
addFirst() - inserts the specified element at the beginning of the array
deque
addLast() - inserts the specified at the end of the array deque (equivalent
to add())
Note: If the array deque is full, all these methods add(), addFirst() and
addLast() throws IllegalStateException.

Example,

import java.util.ArrayDeque;

class Main {
public static void main(String[] args) {
ArrayDeque<String> animals= new ArrayDeque<>();

// Using add()
animals.add("Dog");

// Using addFirst()
animals.addFirst("Cat");

// Using addLast()
animals.addLast("Horse");
System.out.println("ArrayDeque: " + animals);
}
}

More Methods:

offer() - inserts the specified element at the end of the array deque
offerFirst() - inserts the specified element at the beginning of the array
deque
offerLast() - inserts the specified element at the end of the array deque

Access elements using getFirst() and getLast()

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 16


Dept. of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

getFirst() - returns the first element of the array deque


getLast() - returns the last element of the array deque

Access elements using peek(), peekFirst() and peekLast() method

peek() - returns the first element of the array deque


peekFirst() - returns the first element of the array deque (equivalent to
peek())
peekLast() - returns the last element of the array deque

Remove elements using the remove(), removeFirst(), removeLast()


method

remove() - returns and removes an element from the first element of the
array deque
remove(element) - returns and removes the specified element from the
head of the array deque
removeFirst() - returns and removes the first element from the array deque
(equivalent to remove())
removeLast() - returns and removes the last element from the array deque

Iterator

In Java, Iterator is an interface available in Collection framework in java.util package.


It is a Java Cursor used to iterate a collection of objects.

It is used to traverse a collection object elements one by one.


It is available since Java 1.2 Collection Framework.
It is applicable for all Collection classes. So it is also known as Universal
Java Cursor.
It supports both READ and REMOVE Operations.
Compare to Enumeration interface, Iterator method names are simple and
easy to use.

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 17


Dept. of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

Java Iterator Class Diagram

As shown in the Class Diagram below, Java Iterator has four methods. We are
already familiar with first four methods. Oracle Corp has added fourth method to this
interface in Java SE 8 release.

Java Iterator Methods


In this section, we will discuss about Java Iterator methods in-brief. We
will explore these methods in-depth with some useful examples in the
coming section.

boolean hasNext():Returns true if the iteration has more elements.


E next(): Returns the next element in the iteration.
default void remove(): Removes from the underlying collection the last
element returned by this iterator.
default void forEachRemaining(Consumer action): Performs the given action for
each remaining element until all elements have been processed or the action throws
an exception.

Example-1
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public class ExternalIteratorDemo


{
public static void main(String[] args)
{

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 18


Dept. of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

List<String> names = new LinkedList<>();


names.add("Rams");
names.add("Posa");
names.add("Chinni");

// Getting Iterator
Iterator<String> namesIterator = names.iterator();

// Traversing elements
while(namesIterator.hasNext()){
System.out.println(namesIterator.next());
}

}
}
Example-2:-

import java.util.LinkedList;
import java.util.List;

public class InternalIteratorDemo


{
public static void main(String[] args)
{
List<String> names = new LinkedList<>();
names.add("Rams");
names.add("Posa");
names.add("Chinni");

for(String name: names){


System.out.println(name);
}

}
}

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 19


Dept. of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

Map interfaces and classes:


A Map is an ob ject th at map s keys to valu es,or is a collection of attrib u te-valu e p airs. It mod els
th e fu n ction ab straction in math ematics. T h e follow in g p ictu re illu strates a map :

Characteristics of a Map:
B ecau se a Map is n ot a tru e collection ,its ch aracteristics an d b eh aviors are d ifferen t th an th e oth er
collection s like List or Set.

A Map can n ot con tain d u p licate keys an d each key can map to at most on e valu e. S ome
imp lemen tation s allow n u ll key an d n u ll valu e (HashMap an d LinkedHashMap) b u t some d oes
n ot (TreeMap).

1.Why and When Use Maps:


Maps are perfectly for key-value association mapping such as dictionaries.
Use Maps when you want to retrieve and update elements by keys, or
perform lookups by keys. Some examples:
A map of error codes and their descriptions.
A map of zip codes and cities.
A map of managers and employees. Each manager (key) is associated
with a list of employees (value) he manages.
A map of classes and students. Each class (key) is associated with a list
of students (value).
This tutorial provides code examples around the three major
implementations of Map which are described below.

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 20


Dept. of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

2. Implementations of Map
In the inheritance tree of the Map interface, there are several
implementations but only 3 major, common, and general purpose
implementations - they are HashMap and LinkedHashMap and TreeMap.
Let’s see the characteristics and behaviors of each implementation:
HashMap: this implementation uses a hash table as the underlying data
structure. It implements all of the Map operations and allows null values
and one null key. This class is roughly equivalent to Hashtable - a legacy
data structure before Java Collections Framework, but it is not
synchronized and permits nulls. HashMap does not guarantee the order of
its key-value elements. Therefore, consider to use a HashMap when order
does not matter and nulls are acceptable.
LinkedHashMap: this implementation uses a hash table and a linked list
as the underlying data structures, thus the order of a LinkedHashMap is
predictable, with insertion-order as the default order. This implementation
also allows nulls like HashMap. So consider using a LinkedHashMap
when you want a Map with its key-value pairs are sorted by their insertion
order.
TreeMap: this implementation uses a red-black tree as the underlying data
structure. A TreeMap is sorted according to the natural ordering of its
keys, or by a Comparator provided at creation time. This implementation
does not allow nulls. So consider using a TreeMap when you want a Map
sorts its key-value pairs by the natural order of the keys (e.g. alphabetic
order or numeric order), or by a custom order you specify.
So far you have understood the key differences of the 3 major Map’s
implementations. And the code examples in this tutorial are around them.
Now, let’s see how to use Map for your daily coding.

3. Creating a new Map


Creating a HashMap:
Always use interface type (Map), generics and diamond operator to
declare a new map. The following code creates a HashMap:

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

mapHttpErrors.put(200, "OK");
mapHttpErrors.put(303, "See Other");
mapHttpErrors.put(404, "Not Found");

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 21


Dept. of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

mapHttpErrors.put(500, "Internal Server Error");

System.out.println(mapHttpErrors);
This maps HTTP status codes to their descriptions.
Map<Integer, String> mapErrors = new HashMap<>(mapHttpErrors);
The map mapErrors is created with initial elements copied from the map
mapHttpErrors.

Creating a LinkedHashMap:
The following code creates a LinkedHashMap that maps phone numbers
with contact names:

Map<String, String> mapContacts = new LinkedHashMap<>();

mapContacts.put("0169238175", "Tom");
mapContacts.put("0904891321", "Peter");
mapContacts.put("0945678912", "Mary");
mapContacts.put("0981127421", "John");

System.out.println(mapContacts);

Creating a TreeMap:
The following code creates a TreeMap that maps file extensions to
programming languages:
Map<String, String> mapLang = new TreeMap<>();

mapLang.put(".c", "C");
mapLang.put(".java", "Java");
mapLang.put(".pl", "Perl");
mapLang.put(".cs", "C#");
mapLang.put(".php", "PHP");
mapLang.put(".cpp", "C++");
mapLang.put(".xml", "XML");

System.out.println(mapLang);
Output:
1

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 22


Dept. of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

{.c=C, .cpp=C++, .cs=C#, .java=Java, .php=PHP, .pl=Perl, .xml=XML}


As you can see, the TreeMap sorts its keys by their natural ordering,
which is the alphabetical order in this case.

4. Performing Basic Operations on a Map


The basic operations of a Map are association (put), lookup (get),
checking (containsKeyand containsValue), modification (removeand
replace) and cardinality (size and isEmpty).

Associating a value with a key:


The put(K, V) method associates the specified value V with the specified
key K. If the map already contains a mapping for the key, the old value is
replaced by the specified value:

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


mapHttpErrors.put(400, "Bad Request");
mapHttpErrors.put(304, "Not Modified");
mapHttpErrors.put(200, "OK");
mapHttpErrors.put(301, "Moved Permanently");
mapHttpErrors.put(500, "Internal Server Error");

Getting a value associated with a specified key:


The get(Object key) method returns the value associated with the
specified key, or returns null if the map contains no mapping for the key.
Given the map in the previous example:
1
2
String status301 = mapHttpErrors.get(301);
System.out.println("301: " + status301);
Output:
1
301: Moved Permanently

Checking if the map contains a specified key:


The method containsKey(Object key) returns true if the map contains a
mapping for the specified key. For example:
1

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 23


Dept. of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

2
3
if (mapHttpErrors.containsKey("200")) {
System.out.println("Http status 200");
}
Output:
1
Found: Http status 200

Checking if the map contains a specified value:


The method containsValue(Object value) returns true if the map contains
one or more keys associated with the specified value. For example:
1
2
3
if (mapHttpErrors.containsValue("OK")) {
System.out.println("Found status OK");
}

Removing a mapping from the map:


The remove(Object key) method removes the mapping for a key from the
map if it is present (we care about only the key, and the value does not
matter). This method returns the value to which the map previously
associated the key, or null if the map doesn’t contain mapping for the key.
Here’s an example:

String removedValue = mapHttpErrors.remove(500);

if (removedValue != null) {
System.out.println("Removed value: " + removedValue);
}

Removed value: Internal Server Error


Similarly, the remove(Object key, Object value) method removes the
mapping of a specified key and specified value, and returns true if the

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 24


Dept. of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

value was removed. This method is useful in case we really care about the
key and value to be removed.
I recommend you to read this well-know Java collection book to learn in-
depth about Java collections framework.

Replacing a value associated with a specified key:


The replace(K key, V value)method replaces the entry for the specified
key only if it is currently mapping to some value. This method returns the
previous value associated with the specified key.

System.out.println("Map before: " + mapHttpErrors);

mapHttpErrors.replace(304, "No Changes");

System.out.println("Map after: " + mapHttpErrors);

Map before: {400=Bad Request, 304=Not Modified, 200=OK, 301=Moved


Permanently}
Map after: {400=Bad Request, 304=No Changes, 200=OK, 301=Moved
Permanently}
Similarly, the replace(K key, V oldValue, V newValue) method replaces
the entry for the specified key only if it is currently mapping to the specified
value. This method returns true if the value was replaced. Useful in case
we want to replace exactly a key-value mapping.

Getting the size of the map:


The size()method returns the number of key-value mappings in this map.
For example:
1
int size = mapHttpErrors.size();
Output:
1
Number of HTTP status code: 5

Checking if the map is empty:


The isEmpty() method returns true if the map contains no key-value
mappings. For example:

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 25


Dept. of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

1
2
3
4
5
if (mapHttpErrors.isEmpty()) {
System.out.println("No Error");
} else {
System.out.println("Have HTTP Errors");
}
Output:
1
Have HTTP Errors

5. Iterating Over a Map (using Collection views)


As a Map is not a true collection, there is no direct method for iterating
over a map. Instead, we can iterate over a map using its collection views.
Any Map’s implementation has to provide the following three Collection
view methods:
keySet(): returns a Set view of the keys contained in the map. Hence we
can iterate over the keys of the map as shown in the following example:

Map<String, String> mapCountryCodes = new HashMap<>();

mapCountryCodes.put("1", "USA");
mapCountryCodes.put("44", "United Kingdom");
mapCountryCodes.put("33", "France");
mapCountryCodes.put("81", "Japan");

Set<String> setCodes = mapCountryCodes.keySet();


Iterator<String> iterator = setCodes.iterator();

while (iterator.hasNext()) {
String code = iterator.next();
String country = mapCountryCodes.get(code);

System.out.println(code + " => " + country);

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 26


Dept. of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

values(): returns a collection of values contained in the map. Thus we can


iterate over values of the map like this:

Collection<String> countries = mapCountryCodes.values();

for (String country : countries) {


System.out.println(country);
}
Set<Map.Entry<String, String>> entries = mapCountryCodes.entrySet();

for (Map.Entry<String, String> entry : entries) {


String code = entry.getKey();
String country = entry.getValue();

System.out.println(code + " => " + country);


}

mapCountryCodes.forEach(
(code, country) -> System.out.println(code + " => " + country));

6. Performing Bulk Operations with Maps


There are two bulk operations with maps: clear() and putAll().
The clear() method removes all mappings from the map. The map will be
empty after this method returns. For

The putAll(Map<K, V> m) method copies all of the mappings from the
specified map to this map. Here’s an example:
Map<Integer, String> countryCodesEU = new HashMap<>();

countryCodesEU.put(44, "United Kingdom");


countryCodesEU.put(33, "France");
countryCodesEU.put(49, "Germany");

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

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 27


Dept. of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

countryCodesWorld.put(1, "United States");


countryCodesWorld.put(86, "China");
countryCodesWorld.put(82, "South Korea");

System.out.println("Before: " + countryCodesWorld);

countryCodesWorld.putAll(countryCodesEU);

System.out.println("After: " + countryCodesWorld);

Comparators

Java Comp arator in terface u sed to sort a array or list of ob jects b ased on cu stom ord er. Cu stom
ord erin g of elemen ts is imp osed b y imp lemen tin g Comp arator.comp are() meth od in th e ob jects.

We can use Comparator interface in following situations.

Sort the array or list of objects, but NOT in natural order.


Sort the array or list of objects where we can not modify the object’s source code to
implement Comparable interface.
Sort same list or array of objects on different fields.
Using group by sort on list or array of objects on different fields.

Comparator.compare()
To enable total ordering on objects, we need to create class which implements
Comparator interface. Then we need to override it’s compare(T o1, T o2) method.

It compares its two arguments for order. It returns a negative integer, zero, or a
positive integer as the first argument is less than, equal to, or greater than the second.

The implementor must also ensure that the relation is transitive: ((compare(x, y)>0) &&
(compare(y, z)>0)) implies compare(x, z)>0.

Example:
import java.time.LocalDate;

public class Employee implements Serializable {

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 28


Dept. of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

private static final long serialVersionUID = 1L;

private Long id;


private String name;
private LocalDate dob;

//Getters and Setters

@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ", dob=" + dob + "]";
}
}

Using Comparator

import java.util.Comparator;

public class NameSorter implements Comparator<Employee>


{
@Override
public int compare(Employee e1, Employee e2) {
return e1.getName().compareToIgnoreCase( e2.getName() );
}
}

Collections.sort() and Arrays.sort()


Use Collections.sort(list, Comparator) method sort a list of objects in order
imposed by provided comparator instance.
Use Arrays.sort(array, Comparator) method sort an array of objects in order
imposed by provided comparator instance.
Collections.comparing()
This utility method accepts a function that extracts a sort key for the class. This is
essentially a field on which the class objects will be sorted.

Comparator examples
//Order by name
Comparator.comparing(Employee::getName);

//Order by name in reverse order


Comparator.comparing(Employee::getName).reversed();

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 29


Dept. of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

//Order by id field
Comparator.comparing(Employee::getId);

//Order by employee age


Comparator.comparing(Employee::getDate);
Collections.thenComparing()
This utility method is used for group by sort. Using this method, we can chain
multiple comparators to sort the list or array of objects on multiple fields.

It is very similar to SQL GROUP BY clause to order rows on different fields.

Comparator thenComparing() examples


//Order by name and then by age
Comparator.comparing(Employee::getName)
.thenComparing(Employee::getDob);

//Order by name -> date of birth -> id


Comparator.comparing(Employee::getName)
.thenComparing(Employee::getDob)
.thenComparing(Employee::getId);
Using above syntax, we can create virtually any sorting logic.

Collections.reverseOrder()
This utility method returns a comparator that imposes the reverse of the natural
ordering or total ordering on a collection of objects that implement the Comparable
interface.

Comparator reversed() examples


//Reverse of natural order as specified in
//Comparable interface's compareTo() method

Comparator.reversed();

//Reverse of order by name

Comparator.comparing(Employee::getName).reversed();

Collection Algorithms

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 30

You might also like