0% found this document useful (0 votes)
9 views30 pages

Java Collections Framework Overview

Cfug

Uploaded by

mahimanoharn
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views30 pages

Java Collections Framework Overview

Cfug

Uploaded by

mahimanoharn
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Dept.

of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

UNIT – IV
The Collections Framework ([Link])- 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

[Link]

[Link]

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 [Link].*;

class DemoArrayList{

public static void main(String args[]){

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

[Link]("kmit"); // adding elements

[Link]("Kmec");

[Link]("501");

[Link]("kmit");

[Link](1,"NGIT");

[Link]([Link]());

[Link]([Link]("501"));

[Link]("kmit");

[Link]([Link]("kmit"));

Iterator itr=[Link]();

while([Link]()){

[Link]([Link]());

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 [Link].*;
public class DemoLinked{
public static void main(String args[]){
LinkedList<String> list=new LinkedList<String>();
//Adding elements to the Linked list
[Link]("Sree");
[Link]("Ram");
[Link]("Raj");
//Adding an element to the first position
[Link]("KMIT");
//Adding an element to the last position
[Link]("Sita");
//Adding an element to the 3rd position
[Link](2, "NGIT");

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 6


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

[Link]();

//Removing Last element


[Link]();
[Link](1);
//Iterating LinkedList
Iterator<String> iterator=[Link]();
while([Link]()){
[Link]([Link]());
}
}
}

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

[Link] 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 [Link] 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 [Link];
import [Link].*;

public class SampleHashSet {


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

// Adding new elements to the HashSet


[Link]("Big Data");
[Link]("[Link]");
[Link]("Java");
[Link]("Python");
[Link]("Blockchain");
[Link]("JavaScript");
[Link]("Selenium");
[Link]("AWS");
[Link]("Machine Learning");
[Link]("RPA");

// Adding duplicate elements will be ignored


[Link]("Java");
[Link]("RPA");

[Link](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 = "[Link]";


if([Link](myCourse)) {
[Link](myCourse + " is in the courses list.");
} else {
[Link](myCourse + " is not in the courses list.");
}

// Sorting eduCourses using List


List<String> list = new ArrayList<String>(eduCourses);
[Link](list);

// Printing the sorted elements of the HashSet


[Link]("Printing the Courses in sorted order using List: " +
list);

// Removing items from HashSet using remove()


[Link]("Python");

// Iterating over HashSet items


[Link]("Iterating over course list after removing Python:");
Iterator<String> i = [Link]();
while ([Link]())
[Link]([Link]());

// Creating another object of HashSet


HashSet<String> eduNewCourses = new HashSet<String>();
[Link]("[Link]");
[Link]("Python");
[Link]("Machine Learning");

//Removing all the new elements from HashSet


[Link](eduNewCourses);
[Link]("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

[Link](str->[Link]("Java"));
[Link]("After invoking removeIf() method: "+
eduCourses);

// Removing elements from eduCourses which are specified in


eduNewCourses
[Link](eduNewCourses);
[Link]("HashSet after " + "retainAll() operation : " +
eduNewCourses);

//Removing all the elements available in the set


[Link]();
[Link]("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 [Link];
public class TreeSetExample {
public static void main(String args[]) {
// TreeSet of String Type
TreeSet<String> tset = new TreeSet<String>();

// Adding elements to TreeSet<String>


[Link]("ABC");
[Link]("String");
[Link]("Test");
[Link]("Pen");
[Link]("Ink");
[Link]("Jack");

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 12


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

//Displaying TreeSet
[Link](tset);

// TreeSet of Integer Type


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

// Adding elements to TreeSet<Integer>


[Link](88);
[Link](7);
[Link](101);
[Link](0);
[Link](3);
[Link](222);
[Link](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:

[Link]
public class Employee implements Comparable<Employee> {

private Long id;


private String name;
private LocalDate dob;

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


super();
[Link] = id;
[Link] = name;
[Link] = dob;
}

@Override
public int compareTo(Employee emp) {
return [Link]().compareTo([Link]());
}

//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 [Link]
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 [Link];

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

// Using add()
[Link]("Dog");

// Using addFirst()
[Link]("Cat");

// Using addLast()
[Link]("Horse");
[Link]("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 [Link] 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 [Link];
import [Link];
import [Link];

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<>();


[Link]("Rams");
[Link]("Posa");
[Link]("Chinni");

// Getting Iterator
Iterator<String> namesIterator = [Link]();

// Traversing elements
while([Link]()){
[Link]([Link]());
}

}
}
Example-2:-

import [Link];
import [Link];

public class InternalIteratorDemo


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

for(String name: names){


[Link](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).

[Link] 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<>();

[Link](200, "OK");
[Link](303, "See Other");
[Link](404, "Not Found");

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 21


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

[Link](500, "Internal Server Error");

[Link](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<>();

[Link]("0169238175", "Tom");
[Link]("0904891321", "Peter");
[Link]("0945678912", "Mary");
[Link]("0981127421", "John");

[Link](mapContacts);

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

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

[Link](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<>();


[Link](400, "Bad Request");
[Link](304, "Not Modified");
[Link](200, "OK");
[Link](301, "Moved Permanently");
[Link](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 = [Link](301);
[Link]("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 ([Link]("200")) {
[Link]("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 ([Link]("OK")) {
[Link]("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 = [Link](500);

if (removedValue != null) {
[Link]("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.

[Link]("Map before: " + mapHttpErrors);

[Link](304, "No Changes");

[Link]("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 = [Link]();
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 ([Link]()) {
[Link]("No Error");
} else {
[Link]("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<>();

[Link]("1", "USA");
[Link]("44", "United Kingdom");
[Link]("33", "France");
[Link]("81", "Japan");

Set<String> setCodes = [Link]();


Iterator<String> iterator = [Link]();

while ([Link]()) {
String code = [Link]();
String country = [Link](code);

[Link](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 = [Link]();

for (String country : countries) {


[Link](country);
}
Set<[Link]<String, String>> entries = [Link]();

for ([Link]<String, String> entry : entries) {


String code = [Link]();
String country = [Link]();

[Link](code + " => " + country);


}

[Link](
(code, country) -> [Link](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<>();

[Link](44, "United Kingdom");


[Link](33, "France");
[Link](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

[Link](1, "United States");


[Link](86, "China");
[Link](82, "South Korea");

[Link]("Before: " + countryCodesWorld);

[Link](countryCodesEU);

[Link]("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 [Link] 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.

[Link]()
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 [Link];

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 [Link];

public class NameSorter implements Comparator<Employee>


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

[Link]() and [Link]()


Use [Link](list, Comparator) method sort a list of objects in order
imposed by provided comparator instance.
Use [Link](array, Comparator) method sort an array of objects in order
imposed by provided comparator instance.
[Link]()
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
[Link](Employee::getName);

//Order by name in reverse order


[Link](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
[Link](Employee::getId);

//Order by employee age


[Link](Employee::getDate);
[Link]()
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
[Link](Employee::getName)
.thenComparing(Employee::getDob);

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


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

[Link]()
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

[Link]();

//Reverse of order by name

[Link](Employee::getName).reversed();

Collection Algorithms

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 30

Common questions

Powered by AI

The HashSet class in Java's Collections Framework is characterized by its implementation of the Set interface, which allows it to store unique elements and disallow duplicates . It internally uses a hashtable, making it efficient for operations like add, remove, and contains, as these have constant time complexity O(1) on average due to hashing . However, since a HashSet does not maintain any order of its elements, it's typically used where the order is not important but uniqueness and fast access are critical. The performance is influenced by the quality of the hash function used, as poor hashing can lead to collisions, reducing performance to O(n) in the worst case .

A LinkedHashMap maintains insertion-order using a doubly-linked list running through its entries, which makes it suitable when iteration order needs to reflect the insertion order . This predictability is useful for applications that require a consistent iteration order. In contrast, a TreeMap sorts its entries according to the natural ordering of its keys or by a specified comparator, resulting in a sorted map based on key values . TreeMap is suitable for applications where it's beneficial to access entries in sorted key order. The choice between the two depends on whether the order of insertion or sorted order is more valuable for the specific application scenario .

Choosing between Hashtable and HashMap requires assessing the concurrency requirements versus performance needs. Hashtable is synchronized, making it safe for concurrent use but incurs a performance overhead due to synchronization . This is inherently beneficial in multi-threaded environments where thread safety is critical. In contrast, HashMap is non-synchronized, delivering better performance in non-concurrent contexts or when external synchronization is applied . Given its modern nature and allowance for nulls, HashMap is typically preferred over Hashtable for most single-threaded applications, whereas Hashtable remains useful for legacy systems requiring default synchronization .

HashMap permits one null key and multiple null values, allowing developers flexibility in cases where nullity can be a valid parameter . However, this can obscure logic paths and may require additional nullity checks to maintain data integrity. TreeMap, on the other hand, does not allow null keys due to its reliance on natural ordering (or comparator) for sorting the keys; null keys can result in a NullPointerException . Null values are still permissible, but developers must manage key non-nullability inherently. These differences affect data handling strategies and error management within applications relying on these structures .

The clone() method in ArrayList creates a shallow copy, meaning it copies the list structure but not the elements themselves . If the elements are objects, both the original ArrayList and its clone will reference the same objects. Changes to a mutable element in one list will affect the other, which could lead to unintended consequences if not properly accounted for. In contrast, a deep copy involves recursively copying all elements and any objects they refer to, ensuring complete independence between the original and the copy. Shallow copies are generally cheaper to produce but more risky in terms of unintended data sharing .

The forEachRemaining method, introduced in Java SE 8, provides a more functional approach to iterate through the remaining elements of a collection with a single statement . It accepts a Consumer action, applying this action for each remaining element until all elements have been processed or an exception is thrown. This method can improve iteration efficiency by avoiding the explicit use of loop constructs and iterator methods like hasNext and next. It facilitates cleaner code in situations where functional-style iteration is preferred, especially in parallel processing scenarios .

The Vector class, unlike ArrayList, is synchronized, providing thread safety for concurrent operations . This makes Vector suitable for multi-threaded environments where such synchronization is required. However, this synchronization introduces overhead, which can degrade performance compared to ArrayList, which is not synchronized and can perform better in single-threaded or externally synchronized scenarios . Additionally, vectors contain many legacy methods that are not part of the collections framework, suggesting less adaptability to modern collections APIs . Thus, while Vector is useful for thread-safe operations, ArrayList is preferable for its performance in non-concurrent use cases .

LinkedList and ArrayList both implement the List interface but differ significantly in their performance characteristics. LinkedList, being a doubly-linked list, provides efficient O(1) average time complexity for insertions and deletions at the head or tail, as it merely involves updating node references . Conversely, ArrayList, which is based on a dynamic array, requires O(n) time for insertions and deletions not only because of element shifting but also due to potential array resizing operations . Therefore, LinkedList is typically more efficient than ArrayList for applications involving numerous insertions and deletions, particularly at the start or end of the list .

TreeSet relies on the Comparable interface (or a Comparator) to maintain a sorted order of elements according to their natural ordering . It implements set operations like add, remove, and contains efficiently using this order. Improper implementation of the Comparable interface can result in unpredictable behavior such as insertion anomalies, broken order, and erroneous equivalences, leading to Set violations where duplicates appear or elements are lost. Such issues underscore the importance of adhering to proper comparison logic, ensuring that the compareTo method is consistent with equals to maintain TreeSet integrity .

HashSet relies on the hashCode and equals methods to manage uniqueness and proper storage of elements in its underlying hash table . If these methods are not consistently implemented, objects that should be considered equivalent may end up in different buckets, leading to duplication in the set, or conversely, valid objects may be discarded or inaccessible due to hash collision. This inconsistency violates the contract of the Set interface and can result in subtle, hard-to-diagnose errors during set operations. Ensuring these methods are properly overridden is critical for the reliable functioning of HashSet .

You might also like