Over

120,000

Worldwide

Saturday - Sunday CLOSED

Mon - Fri 8.00 - 18.00

Call us

 

Java Collections Framework

.

Contents

Java Collections Framework  1

1.  Introduction  2

2.  Advantages  2

3.  Interfaces  2

3.1  Iterable  3

3.2  Collection  4

Creating a collection  5

Generics  5

Methods  6

3.3  List  8

3.4  Set  12

3.5  SortedSet  15

3.6  NavigableSet  16

3.7  Queue  18

3.8  Deque  21

3.9  Map  23

3.10  SortedMap  25

3.11  NavigableMap  27

3.12  Iterator  30

3.13  ListIterator  32

4.  Time Complexity – Basic Operations  34

5.  Collections class  34

6.  Properties class  36

7.  Equals() and hashCode()  38

8.  Sorting  41

.

.

.

.

1.Introduction

.

 A Collection is a group of objects that are represented as a single unit.
 The Java Collections framework consists of interfaces, classes and algorithms that provide an architecture for representing and manipulating collections.
 All common operations such as add, remove, update, search and sort can be performed on collections.
 The java.util package contains all the classes and interfaces of the Collection framework.

.

I – interface

C – Class

.

2.Advantages

.

 Reduced development effort as the framework provides ready-to-use classes and algorithms so the developers do not need to design and implement themselves.
 Enhanced code quality and performance
 Reusability and interoperability
 Unrelated APIs can exchange collection interfaces

.

3.Interfaces

.

The Collections framework contains interfaces that allow collections to be manipulated independently of the details of their representation.

The core interfaces of the Collections framework are:

.

3.1Iterable

.

       public interface Iterable<T>

.

 Iterable is the root interface of the collections framework.
 All the interfaces and classes, inherently, implement this interface.
 This interface provides an iterator for a collection to have its elements iterated.
 Implementing this interface also allows a collection to be iterated using the for-each loop.

.

Methods:

.

It contains the following methods:

.

 Iterator<T> iterator()

.

This is an abstract method that returns an iterator over the elements of type T.

.

 default void forEach(Consumer<? super T> action)

.

Performs the given action for each element.

.

 default Spliterator<T> spliterator()

.

Creates a Spliterator over the elements. A Spliterator is useful for traversing and partitioning the elements.

.

Examples:

.

Following are some examples showing the different ways of iterating the elements of the collection (list) containing employee names.

.

List<String> employees =

                        Arrays.asList(“Jack”,“Robert”,“David”,“Abhi”,“Daniel”);

.

.

 Iterate using an Iterator

.

.

.

 Iterate using a for-each loop

Iterator<String> employeeIterator = employees.iterator();

while(employeeIterator.hasNext())
{
String emp = employeeIterator.next();
System.out.println(emp);
}

.

for(String emp : employees)
{

System.out.println(emp);
}

.

.

 Iterate using the forEach method

.

employees.forEach(
employee -> {
System.out.println(employee);}
);

.

All the examples above produce the following output:

.

Output:

Jack

Robert

David

Abhi

Daniel

.

.

3.2Collection

.

public interface Collection<E> extends Iterable<E>

.

 The Collection interface extends the Iterable interface, and is implemented by all classes in the Collections framework.
 It contains the core methods are used to perform operations on collections. All the collection classes that implement this interface support these methods.
 This interface does not have a direct implementation; rather it is implemented through other interfaces that extend this interface.

Sub-interfaces of Collection:

Following are the interfaces (types of collections) that directly extend the Collection interfaces:

 List
 Set
 Queue

Creating a collection

.

A Collection is created as an instance of one of the classes that implements the Collection interface e.g. an ArrayList (which implements the List interface).

Collection collection1 = new ArrayList();

.

or to be more specific,

.

List list1 = new ArrayList();

.

We can put any type of object in the collection created above. To retrieve the elements from this list, type-casting is required otherwise the compiler does not know what data type is returned.

List list1 = new ArrayList();
list1.add(new String(“hello”)); //add an object of String type
String str = (String) list1.iterator().next(); // type-casting

.

Further, there is no guarantee that the list always has the objects of String type, so it could lead to a runtime exception while retrieving the elements from the list.

List list1 = new ArrayList();
list1.add(new String(“hello”)); //add an object of String type
list1.add(1); //add an object of Integer type
Iterator iterator = list1.iterator();
while(iterator.hasNext())
{

String str = (String) iterator.next();
System.out.println(str);
}

.

Output:

.

hello

Exception in thread “main” java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.String

.

.

Generics

.

The concept of Generics, introduced in Java 5, allows us to declare the type of objects that a collection will store.

 The generic collections are type-safe and checked at compile-time.
 The generic collections do not require type-casting.
 While declaring a collection variable, its generic type can be given as a parameter using the diamond operator ‘<>’.

Below is the example of a collection that will contain only String type of objects.

List<String> list1 = new ArrayList();
list1.add(new String(“hello”));
list1.add(new String(“world”));
Iterator iterator = list1.iterator();
while(iterator.hasNext())
{

String str = (String) iterator.next();
System.out.println(str);
}

Output:

.

hello

world

.

A compile-time error is generated if we try to add another type of object.

List<String> list1 = new ArrayList();
list1.add(new String(“hello”));
list1.add(1); // compile-time error

Methods

.

Following are the core methods of collection interface:

 add(Object o) : Add the given element to the collection

.

 addAll(Collection c) : Adds all the elements in the given collection to the target collection

.

 remove(Object o) : Removes the given element from the collection

.

 removeAll(Collection c) : Removes all the elements in the given collection from the target collection

.

 contains(Object o) : Returns true if the collection contains the given element

.

 containsAll(Collection c) : Returns true if the target collection contains all the elements of the given collection

.

 size() : Returns the number of elements in the collection

.

 retainAll(Collection c) : Retains in the target collection only the elements of the given collection

.

 iterator() : Returns an iterator over the elements of the collection

.

 clear() : Removes all the elements from the collection

.

Examples:

The example below shows the usage of each of the above methods.

A collection ‘employees’ of objects of String type is used to store and manipulate a list of employees’ names.

//create a collection

Collection employees = new ArrayList<>();
System.out.println(“Employees list no elements: ” + employees);

//add
employees.add(“Jack”);
System.out.println(“Employees list after adding element: ” + employees);
employees.add(“Abhi”);
System.out.println(“Employees list after adding element: ” + employees);

//addAll
Collection newEmployees = new ArrayList<>();
newEmployees.add(“Daniel”);
newEmployees.add(“Robert”);
newEmployees.add(“Nick”);
newEmployees.add(“Ankit”);
newEmployees.add(“Nilton”);
newEmployees.add(“John”);
newEmployees.add(“Tom”);
employees.addAll(newEmployees);
System.out.println(“Employees list after adding a collection: ” + employees);

//remove
employees.remove(“Abhi”);
System.out.println(“Employees list after removing an element: ” + employees);

//removeAll
Collection oldEmployees = new ArrayList<>();
oldEmployees.add(“Jack”);
oldEmployees.add(“Daniel”);
employees.removeAll(oldEmployees);
System.out.println(“Employees list after removing a collection: ” + employees);

//contains
String checkEmployee = “Robert”;
boolean employeeFound = employees.contains(checkEmployee);
System.out.println(“Employees list ” + employees + ” contains ” + checkEmployee + “? ” + employeeFound);
checkEmployee =
“Abhi”;
employeeFound =
employees.contains(checkEmployee);
System.out.println(“Employees list ” + employees + ” contains ” + checkEmployee + “? ” + employeeFound);

//containsAll
Collection checkEmployees = new ArrayList<>();
checkEmployees.add(“Jack”);
checkEmployees.add(“Daniel”);
checkEmployees.add(“Abhi”);
checkEmployees.add(“Robert”);
checkEmployees.add(“Nick”);
boolean employeesFound = employees.containsAll(checkEmployees);
System.out.println(“Employees list ” + employees + ” contains ” + checkEmployees + “? ” + employeesFound);

//size
int employeeCount = employees.size();
System.out.println(“Employees list ” + employees + ” size: ” + employeeCount);

//retainAll
Collection retainEmployees = new ArrayList<>();
retainEmployees.add(“Tom”);
retainEmployees.add(“John”);
employees.retainAll(retainEmployees);
System.out.println(“Employees list after retaining a collection: ” + employees);

//iterator
Iterator employeeIterator = employees.iterator();
while(employeeIterator.hasNext())
{

System.out.println(“Employee: “+ employeeIterator.next());
}

//clear
employees.clear();
System.out.println(“Employees list after clear: ” + employees);

.

Output:

.

Employees list no elements: []

Employees list after adding element: [Jack]

Employees list after adding element: [Jack, Abhi]

Employees list after adding a collection: [Jack, Abhi, Daniel, Robert, Nick, Ankit, Nilton, John, Tom]

Employees list after removing an element: [Jack, Daniel, Robert, Nick, Ankit, Nilton, John, Tom]

Employees list after removing a collection: [Robert, Nick, Ankit, Nilton, John, Tom]

Employees list [Robert, Nick, Ankit, Nilton, John, Tom] contains Robert? true

Employees list [Robert, Nick, Ankit, Nilton, John, Tom] contains Abhi? false

Employees list [Robert, Nick, Ankit, Nilton, John, Tom] contains [Jack, Daniel, Abhi, Robert, Nick]? false

Employees list [Robert, Nick, Ankit, Nilton, John, Tom] size: 6

Employees list after retaining a collection: [John, Tom]

Employee: John

Employee: Tom

Employees list after clear: []

.

3.3List

.

.

public interface List<E> extends Collection<E>

.

 The List interface extends the Collection interface.
 A List represents an ordered collection of elements.
 A List allows duplicate and null elements.
 A List uses an index, starting from 0, to store its elements. This index is used to access and perform operations on elements in a list.
 List is typically used in scenarios where you just want to store some objects and iterate through them later.

Some classes which implement List interface are:

1.ArrayList
 Resizable-array implementation of List interface.
 It should be used when storing and retrieving of elements is only expected.

.

2.LinkedList
 Doubly-linked list implementation of the List and Deque interfaces.
 It should be used when frequent modifications to the collection are expected, because it is faster than ArrayList in such cases.

.

3.Vector
 It is a legacy class.
 Implements a growable array of objects.
 It is thread-safe.

.

4.Stack
 represents a last-in-first-out (LIFO) stack of objects.

Creating a List:

A List is created as an instance of one of the classes that implements the List interface.

Creating an ArrayList of type String:

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

Creating an ArrayList of type Employee:

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

Creating a LinkedList of type String:

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

Creating a LinkedList of type Employee:

List<Employee> list = new LinkedList <>();

.

Methods

Following are the additional methods of the List interface:

 boolean add(int index, Object o) : Add the given element to the list at the given index

.

 boolean addAll(int index, Collection c) : Adds all the elements in the given collection to the target list at the given index

.

 Object get(int index) : Returns the element stored at the given index in the list

.

 int indexOf(Object o) : Returns the index of the first occurrence of the given element in the list

.

 int lastIndexOf(Object o) : Returns the index of the last occurrence of the given element in the list

.

 Object remove(int index) : Removes the element at the given index from the list

.

 List subList(int start, int end) : Returns a list with elements from the ‘start’ index to the ‘end’ index of a list

Examples:

1.The example below shows the usage of each of the above methods on a list.

//create a list
List<String> employees = new ArrayList<>();
System.out.println(“Employees list no elements: ” + employees);

//add
employees.add(“Jack”);
System.out.println(“Employees list after adding element: ” + employees);
employees.add(“Abhi”);
System.out.println(“Employees list after adding element: ” + employees);

//add at specific index
employees.add(0,“Daniel”);
System.out.println(“Employees list after adding element at index 0: ” + employees);

employees.add(2,“Robert”);
System.out.println(“Employees list after adding element at index 2: ” + employees);
//addAll
List<String> newEmployees = new ArrayList<>();
newEmployees.add(“Nick”);
newEmployees.add(“Ankit”);
newEmployees.add(“Nilton”);
newEmployees.add(“John”);
newEmployees.add(“Abhi”); //duplicate allowed
employees.addAll(newEmployees);
System.out.println(“Employees list after adding another list: ” + employees);

//get from given index
System.out.println(“Employee at index 4: ” + employees.get(4));
System.out.println(“Employee at index 1: ” + employees.get(1));

//get index of element
String emp = “Abhi”;
System.out.println(“Employees list contains first occurrence of ” +emp+ ” at index: “+ employees.indexOf(emp));
System.out.println(“Employees list contains last occurrence of ” +emp+ ” at index: “+ employees.lastIndexOf(emp));

//remove from given index
employees.remove(0);
System.out.println(“Employees list after removing an element from index 0: ” + employees);

//contains
String checkEmployee = “Kris”;
boolean employeeFound = employees.contains(checkEmployee);
System.out.println(“Employees list ” + employees + ” contains ” + checkEmployee + “? ” + employeeFound);

//sub-list
List<String> subList = employees.subList(1,4);
System.out.println(“Employees sub-list: ” + subList);

//clear
employees.clear();
System.out.println(“Employees list after clear: ” + employees);

}

Output:

.

Employees list no elements: []

Employees list after adding element: [Jack]

Employees list after adding element: [Jack, Abhi]

Employees list after adding element at index 0: [Daniel, Jack, Abhi]

Employees list after adding element at index 2: [Daniel, Jack, Robert, Abhi]

Employees list after adding another list: [Daniel, Jack, Robert, Abhi, Nick, Ankit, Nilton, John, Abhi]

Employee at index 4: Nick

Employee at index 1: Jack

Employees list contains first occurrence of Abhi at index: 3

Employees list contains last occurrence of Abhi at index: 8

Employees list after removing an element from index 0: [Jack, Robert, Abhi, Nick, Ankit, Nilton, John, Abhi]

Employees list [Jack, Robert, Abhi, Nick, Ankit, Nilton, John, Abhi] contains Kris? false

Employees sub-list: [Robert, Abhi, Nick]

Employees list after clear: []

.

2.The example below shows the conversion between an array and a list.

String[] array1 = new String[] {“Jack”, “Nick”, “Dan”, “Tom”};

//array to list
List<String> list = Arrays.asList(array1);

//list to array
String[] array2 = list.toArray(new String[]{});

.

.

.

.

.

3.4Set

.

public interface Set<E> extends Collection<E>

.

 The Set interface extends the Collection interface.
 A Set cannot contain duplicate elements.
 A Set is used when the requirement is to have only unique values in the collection.

The classes which implement Set interface are:

1.HashSet
 stores its elements in a hash table.
 It has better performance than the TreeSet and LinkedHashset
 It is used when the order of insertion of elements is not important.

.

2.LinkedHashSet
 Implemented as a hash table with a linked list.
 Its performance is slightly slower than HashSet but faster than TreeSet as it has to maintain the insertion order of elements.
 It is used when insertion order of elements is to be maintained.

.

3.TreeSet
 Stores its elements in a tree, based on the natural ordering or on the basis of a comparator.
 Its performance is slower than HashSet and LinkedHashSet because it has perform sorting after each insertion and deleting.
 It is used when unique elements are required to be stored in a sorted order.

.

Creating a Set:

A Set is created as an instance of one of the classes that implements the Set interface.

Creating a HashSet of type Integer:

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

Creating a HashSet of type Employee:

Set<Employee> list = new HashSet<>();

Methods

The Set interface contains only methods inherited from the Collection interface.

Examples:

1.The example below usage of set to remove duplicate elements from a list.

.

.

2.The example below shows common operations on a set.

//create a list
List<String> employees = new ArrayList<>();

//add
employees.add(“Jack”);
employees.add(“Abhi”);
employees.add(“Daniel”);
employees.add(“Ankit”);
employees.add(“Nilton”);
employees.add(“Abhi”); // duplicate
employees.add(“Daniel”); // duplicate

System.out.println(“Employees list with duplicate elements: ” + employees);

//create a set from the list
Set<String> employeeSet = new HashSet<>(employees);

System.out.println(“Employees set: ” + employeeSet);

.

Output:

.

Employees list with duplicate elements: [Jack, Abhi, Daniel, Ankit, Nilton, Abhi, Daniel]

Employees set: [Nilton, Daniel, Jack, Abhi, Ankit]

//create a set
Set<String> employees = new HashSet<>();
System.out.println(“Employees set no elements: ” + employees);

//add
employees.add(“Jack”);
employees.add(“Abhi”);
employees.add(“Ankit”);
System.out.println(“Employees set after adding elements: ” + employees);

//addAll
List<String> newEmployees = new ArrayList<>();
newEmployees.add(“Nick”);
newEmployees.add(“Ankit”);
newEmployees.add(“Nilton”);
newEmployees.add(“John”);
newEmployees.add(“Abhi”); //duplicate will not be added
employees.addAll(newEmployees);
System.out.println(“Employees set after adding from a list: ” + employees);

//contains
String checkEmployee = “Kris”;
boolean employeeFound = employees.contains(checkEmployee);
System.out.println(“Employees set ” + employees + ” contains ” + checkEmployee + “? ” + employeeFound);

//remove
employees.remove(“Nick”);
System.out.println(“Employees set after removing element: ” + employees);

//size
System.out.println(“Employees set contains ” + employees.size() + ” employees.”);

//iterator
Iterator iterator = employees.iterator();
while(iterator.hasNext()) {
System.out.println(iterator.next()+“,”);
}

//clear
employees.clear();
System.out.println(“Employees set after clear: ” + employees);

Output:

.

Employees set no elements: []

Employees set after adding elements: [Jack, Abhi, Ankit]

Employees set after adding from a list: [Nick, Nilton, John, Jack, Abhi, Ankit]

Employees set [Nick, Nilton, John, Jack, Abhi, Ankit] contains Kris? false

Employees set after removing element: [Nilton, John, Jack, Abhi, Ankit]

Employees set contains 5 employees.

Nilton,

John,

Jack,

Abhi,

Ankit,

Employees set after clear: []

.

3.The example below shows the basic mathematical operations (union, difference, intersection) on a set.

//first set
Set<Integer> setA = new HashSet<>();
setA.addAll(Arrays.asList(9,7,3,2,1,0,15));
System.out.println(“Set A: “+setA);

//second set
Set<Integer> setB = new HashSet<>();
setB.addAll(Arrays.asList(5,9,3,2,4,6));
System.out.println(“Set B: “+setB);

//union
Set<Integer> union = new HashSet<>(setA);
union.addAll(setB);
System.out.println(“Union of two sets: “+union);

//intersection
Set<Integer> intersect = new HashSet<>(setA);
intersect.retainAll(setB);
System.out.println(“Intersection of two sets: “+intersect);

//difference
Set<Integer> diff = new HashSet<>(setA);
diff.removeAll(setB);
System.out.println(“Difference of two sets: “+diff);

Output:

.

Set A: [0, 1, 2, 3, 7, 9, 15]

Set B: [2, 3, 4, 5, 6, 9]

Union of two sets: [0, 1, 2, 3, 4, 5, 6, 7, 9, 15]

Intersection of two sets: [2, 3, 9]

Difference of two sets: [0, 1, 7, 15]

.

3.5SortedSet

.

public interface SortedSet<E> extends Set<E>

.

 The SortedSet interface extends the Set interface.
 The elements are ordered using their natural ordering, or on the basis of a Comparator.
 By default, the elements of a sorted set are iterated in ascending order.

The class which implements the SortedSet interface:

TreeSet

 Stores its elements in a tree, in an order based on the values. It is slower than the hashset.

.

Creating a SortedSet of type Integer (using natural ordering):

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

.

Creating a SortedSet of type Employee (using comparator):

Comparator comparator = new EmployeeComparator();

SortedSet<Employee> set = new TreeSet<>(comparator);

.

Methods

The SortedSet interface contains the following methods in addition to the methods inherited from the Set interface.

 Comparator comparator() : Returns the comparator used to order the elements in this set, or null if the set uses natural ordering.

.

 SortedSet subset(E fromElement, E toElement) : Returns the elements that occur between fromElement and toElement, including fromElement.

.

 SortedSet headset(E toElement) : Returns the elements that are less than (occur before) the toElement.

.

 SortedSet tailSet(E fromElement) : Returns the elements that are greater than or equal to fromElement.

.

 E first() : Returns the first (lowest) element in the sorted set.

.

 E last() : Returns the last (highest) element in the sorted set.

.

Examples:

1.The example below usage of above methods with a sorted set.

.

.

SortedSet<Integer> set = new TreeSet<>();
set.add(9);
set.add(1);
set.add(3);
set.add(8);
set.add(7);
set.add(2);
System.out.println(“sorted set: “+ set);

//first
System.out.println(“first element: “+ set.first());

//last
System.out.println(“last element: “+ set.last());

//subSet
System.out.println(“subset: “+ set.subSet(2,8));

//headSet
System.out.println(“headset: “+ set.headSet(7));

//tailSet
System.out.println(“tailset: “+ set.tailSet(7));

.

Output:

.

sorted set: [1, 2, 3, 7, 8, 9]

first element: 1

last element: 9

subset: [2, 3, 7]

headset: [1, 2, 3]

tailset: [7, 8, 9]

1.6NavigableSet

.

public interface NavigableSet<E> extends SortedSet<E>

.

 The NavigableSet interface extends the SortedSet interface.
 It provides additional methods for navigation through the sorted set.
 The NavigableSet can be iterated in ascending or descending order.

The class which implements the NavigableSet interface:

TreeSet

 A NavigableSet implementation based on a Treemap.

Creating a NavigableSet of type Integer (using natural ordering):

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

.

Methods

The NavigableSet interface contains the following methods in addition to the methods inherited from the SortedSet interface:

 E lower(E element) : Returns the greatest element in the set that is less than the given element.

.

 E floor(E element) : Returns the greatest element in the set that is less than or equal to the given element.

.

 E ceiling(E element) : Returns the least element in the set that is greater than or equal to the given element.

.

 E higher(E element) : Returns the least element in the set that is greater than the given element.

.

 E pollFirst() : Returns and removes the first (lowest) element in the set.

.

 E pollLast() : Returns and removes the last (highest) element in the set.

.

 NavigableSet descendingSet(): Returns a reverse order view of the elements in the set.

.

 NavigableSet subset(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) : Returns the elements that occur between fromElement and toElement. fromElement and toElement are included in the result based on the value of fromInclusive and toInclusive, respectively.

.

 NavigableSet headset(E toElement, boolean inclusive) : Returns the elements that are less than (or equal to, if inclusive in true) the toElement.

.

 NavigableSet tailSet(E fromElement, Boolean inclusive) : Returns the elements that are greater than (or equal to, if inclusive is true) the fromElement.

.

.

Examples:

1.The example below usage of above methods with a navigable set.

.

NavigableSet<Integer> set = new TreeSet<>();
set.add(9);
set.add(1);
set.add(3);
set.add(8);
set.add(7);
set.add(2);
System.out.println(“Set ascending order: “+ set);

//reverse order
System.out.println(“Set reverse order: “+ set.descendingSet());

//lower
System.out.println(“lower(7): “+ set.lower(7));

//floor
System.out.println(“floor(7): “+ set.floor(7));

//ceiling
System.out.println(“ceiling(7): “+ set.ceiling(7));

//higher
System.out.println(“higher(7): “+ set.higher(7));

//subset
System.out.println(“subset(2,8) both excluded: “+ set.subSet(2,false,8,false));

//headset
System.out.println(“headset(3) included: “+ set.headSet(3,true));

//tailSet
System.out.println(“tailset(3) excluded: “+ set.tailSet(3, false));

//poll first
System.out.println(“poll first: “+ set.pollFirst() + “; set: ” + set);

//poll last
System.out.println(“poll last: “+ set.pollLast() + “; set: ” + set);

.

Output:

.

Set ascending order: [1, 2, 3, 7, 8, 9]

Set reverse order: [9, 8, 7, 3, 2, 1]

lower(7): 3

floor(7): 7

ceiling(7): 7

higher(7): 8

subset(2,8) both excluded: [3, 7]

headset(3) included: [1, 2, 3]

tailset(3) excluded: [7, 8, 9]

poll first: 1; set: [2, 3, 7, 8, 9]

poll last: 9; set: [2, 3, 7, 8]

1.7Queue

.

public interface Queue<E> extends Collection<E>

.

 A Queue represents a collection in which elements are inserted at the end, and removed from the beginning of the queue.
 Queues typically order elements in a FIFO (First In First Out) manner.
 It is used when you want elements in the order that they were inserted.

The class which implements the Queue interface:

1.LinkedList
 The elements are stored in a standard linked list data structure.
 It is a standard linked list that can be used as a queue.

.

2.PriorityQueue
 The elements of the priority queue are ordered according to their natural ordering, or by using a Comparator.
 It is used when the highest priority element should be at the head of the queue.

Creating a Queue of type Integer:

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

Creating a Queue of type String (using a comparator):

Comparator<String> comparator = new MyComparator();

Queue<String> queue = new PriorityQueue<>(comparator);

.

Methods

The Queue interface contains the following methods in addition to the methods inherited from the Collection interface:

 boolean add(E element) : Inserts the given element into the queue and returns true. This method throws an exception when the capacity of the queue is full.

.

 boolean offer(E element) : Inserts the given element into the queue and returns true. This method does not throw an exception when the capacity of the queue is full, instead it returns false.

.

 E remove() : Returns and removes the element at the head of the queue. This method throws exception if the queue is empty.

.

 E poll() : Returns and removes the element at the head of the queue. This method returns null if the queue is empty.

.

 E element() : Returns the element at the head of the queue. This method throws exception if the queue is empty.

.

 E peek() : Returns the element at the head of the queue. This method returns null if the queue is empty.

.

Examples:

1.The example below shows the LinkedList implementation of a queue.

.

2.The example below shows the PriorityQueue implementation of a queue, using a comparator based on the length of strings.

//create a queue and add elements

Queue<String> queue = new LinkedList<>();
queue.offer(“Ankit”);
queue.offer(“Daniel”);
queue.offer(“Nilton”);
queue.offer(“Tom”);
queue.offer(“Harry”);
System.out.println(“Queue: “+ queue);

//peek
System.out.println(“peek: “+ queue.peek());

//poll
System.out.println(“poll: “+ queue.poll());
System.out.println(“Queue: “+ queue);

//peek
System.out.println(“peek: “+ queue.peek());

//poll
System.out.println(“poll: “+ queue.poll());
System.out.println(“Queue: “+ queue);

//poll
System.out.println(“poll: “+ queue.poll());
System.out.println(“Queue: “+ queue);

.

Output:

.

Queue: [Ankit, Daniel, Nilton, Tom, Harry]

peek: Ankit

poll: Ankit

Queue: [Daniel, Nilton, Tom, Harry]

peek: Daniel

poll: Daniel

Queue: [Nilton, Tom, Harry]

poll: Nilton

Queue: [Tom, Harry]

//create a comparator

Comparator<String> comparator = new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.length() – o2.length();
}

};
.

//create a queue and add elements
Queue<String> queue = new PriorityQueue<>(comparator);
queue.offer(“Ankit Singhal”);
queue.offer(“D Sean”);
queue.offer(“Nilton Santos”);
queue.offer(“Harry Fernandez”);
System.out.println(“Queue: “+ queue);

//peek
System.out.println(“peek: “+ queue.peek());

//poll
System.out.println(“poll: “+ queue.poll());
System.out.println(“Queue: “+ queue);

//peek
System.out.println(“peek: “+ queue.peek());

//poll
System.out.println(“poll: “+ queue.poll());
System.out.println(“Queue: “+ queue);

//poll
System.out.println(“poll: “+ queue.poll());
System.out.println(“Queue: “+ queue);

.

Output:

.

Queue: [D Sean, Ankit Singhal, Nilton Santos, Harry Fernandez]

peek: D Sean

poll: D Sean

Queue: [Ankit Singhal, Harry Fernandez, Nilton Santos]

peek: Ankit Singhal

poll: Ankit Singhal

Queue: [Nilton Santos, Harry Fernandez]

poll: Nilton Santos

Queue: [Harry Fernandez]

.

1.8Deque

.

public interface Deque<E> extends Queue<E>

.

 A Deque or “double ended queue” represents a queue in which elements can be inserted and removed from both ends.

The major classes which implement the Deque interface:

1.LinkedList

The elements are stored in a standard linked list data structure.

2.ArrayDeque

Resizable-array implementation of the Deque interface.Creating a Queue of type Integer:

.

Create a Deque of type Integer:

Dequeue<Integer> queue = new LinkedList<>();

Dequeue<Integer> queue = new ArrayDeque<>();

.

Methods

This interface defines methods to insert, retrieve and remove the elements at both ends of the deque. Similar to Queue interface, each of these methods exists in two forms: one throws an exception if the operation fails, the other returns a null or false.

.

First Element (Head)

Last Element (Tail)

.

Throws exception

Null or False

Throws exception

Null or False

Insert

addFirst(e)

offerFirst(e)

addLast(e)

offerLast(e)

Remove

removeFirst()

pollFirst()

removeLast()

pollLast()

Retreive

getFirst()

peekFirst()

getLast()

peekLast()

.

Examples:

1.The example below shows the usage of above methods with a deque.

.

//create a dequeue and add elements

Deque<String> queue = new ArrayDeque<>();

//add at beginning
queue.offerFirst(“Ankit”);
System.out.println(“offer first (Ankit): “+ queue);
queue.offerFirst(“Sean”);
System.out.println(“offer first (Sean): “+ queue);
System.out.println(“Queue: “+ queue);

//add at end
queue.offerLast(“Nilton”);
System.out.println(“offer last (Nilton): “+ queue);
queue.offerLast(“Harry”);
System.out.println(“offer last (Harry): “+ queue);

//get from beginning
System.out.println(“peek first: “+ queue.peekFirst());

//remove from beginning
System.out.println(“poll first: “+ queue.pollFirst());
System.out.println(“Queue: “+ queue);

//get from last
System.out.println(“peek last: “+ queue.peekLast());

//poll from last
System.out.println(“poll last: “+ queue.pollLast());
System.out.println(“Queue: “+ queue);

Output:

.

offer first (Ankit): [Ankit]

offer first (Sean): [Sean, Ankit]

Queue: [Sean, Ankit]

offer last (Nilton): [Sean, Ankit, Nilton]

offer last (Harry): [Sean, Ankit, Nilton, Harry]

peek first: Sean

poll first: Sean

Queue: [Ankit, Nilton, Harry]

peek last: Harry

poll last: Harry

Queue: [Ankit, Nilton]

.

1.9Map

.

public interface Map<K,V>

.

 A map stores data in pairs of keys and values. Each key maps to a value and this pair is known as an entry.
 A map cannot contain duplicate keys, and each key can map to at most one value.
 The Map interface provides three collection views, which allow a map’s contents to be viewed as a set of keys, collection of values, or set of key-value mappings.
 It is used when you want to associate a key with a value, and lookup elements by keys.

The classes which implement Map interface are:

1.HashMap
 This is the basic implementation of the Map interface. It uses the ‘hashing’ technique to map the keys and values, for faster operations.
 It has better performance than the TreeMap and LinkedHashMap
 It is used when the order of insertion of elements is not important

.

2.LinkedHashMap
 This class provides additional feature of maintaining the insertion order of elements.
 Its performance is slightly slower than HashMap but faster than TreeMap, as it has to maintain the insertion order of elements.
 It is used when insertion order of elements is to be maintained.

.

3.TreeMap
 This map is sorted in natural order of its keys, or on the basis of a comparator.
 Its performance is slower than HashMap and LinkedHashMap because it has perform sorting after each insertion and deleting.
 It is used when unique elements are required to be stored in a sorted order.

Creating a HashMap with ‘String’ key and ‘Integer’ value:

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

Creating a HashMap with ‘String’ key and ‘Employee’ value:

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

Methods

The Map interface contains the following methods:

  int size() : Returns the number of key-value mappings in the map.

.

 isEmpty() : Returns true if the map contains no key-value mapping.

.

 boolean containsKey(Object key) : Returns true if the map contains a mapping for the given key.

.

 boolean containsValue(Object value) : Returns true if the map contains a key that is mapped to the given value.

.

 V get(Object key) : Returns the value to which the given key is mapped, or null if the map does not contain the key.

.

 V put(K key, V value) : Maps the given key in the map, with the given value. If the map already contains a mapping for the given key, the old value is replaced with the given value.

.

 V remove(Object key) : Removes the mapping for the given key from the map if it is present.

.

 Set<K> keySet() : Returns as a set, all the keys contained in the map.

.

 Collection<V> values : Returns the collection of all the values contained in the map.

.

 Set<Map.Entry<K,V>> entrySet() : Returns as a set all the mappings contained in the map.

.

 Object putAll(Map m) : Put all entries from the given map into the target map.

.

.

Examples:

1.The example below shows the basic operations on a map.

//create a map
Map<String,Integer> employeeRates = new HashMap<>();

//add elements
employeeRates.put(“John”,20);
employeeRates.put(“Tom”,15);
employeeRates.put(“Harry”,45);
employeeRates.put(“Anne”,30);
employeeRates.put(“Mira”,25);

System.out.println(“Initial Map: ” + employeeRates);

//change value
employeeRates.put(“John”,25);
System.out.println(“Map after value update (John): ” + employeeRates);

//remove element
employeeRates.remove(“Mira”);
System.out.println(“Map after remove (Mira): ” + employeeRates);

//keys
System.out.println(“Map keys: ” + employeeRates.keySet());

//values
System.out.println(“Map values: ” + employeeRates.values());

//get value
System.out.println(“Get value (Tom): ” + employeeRates.get(“Tom”));
System.out.println(“Get value (Ankit): ” + employeeRates.get(“Ankit”));

//iterating the map
for(Map.Entry mapElement : employeeRates.entrySet())
{

String key = (String) mapElement.getKey();
Integer value = (Integer) mapElement.getValue();
System.out.println(“Name: “+ key + “; Rate: ” + value);
}

.

Output:

.

Initial Map: {Tom=15, Harry=45, John=20, Anne=30, Mira=25}

Map after value update (John): {Tom=15, Harry=45, John=25, Anne=30, Mira=25}

Map after remove (Mira): {Tom=15, Harry=45, John=25, Anne=30}

Map keys: [Tom, Harry, John, Anne]

Map values: [15, 45, 25, 30]

Get value (Tom): 15

Get value (Ankit): null

Name: Tom; Rate: 15

Name: Harry; Rate: 45

Name: John; Rate: 25

Name: Anne; Rate: 30

.

.

1.10SortedMap

.

public interface SortedMap<K,V> extends Map<K,V>

.

 The SortedMap interface extends the Map interface.
 The elements are ordered using their natural ordering, or on the basis of a Comparator.
 By default, the elements are stored in the ascending order.
 All keys of the sorted map must implement the Comparable interface.

The class which implements the SortedSet interface:

TreeMap

 Stores its elements in a tree, in an order of the keys.

.

Creating a SortedMap (using natural ordering):

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

Creating a SortedMap (using comparator):

Comparator comparator = new EmployeeComparator();

SortedSet<Employee,Integer> map = new TreeMap<>(comparator);

.

Methods

The SortedMap interface contains the following methods in addition to the methods inherited from the Map interface.

 Comparator comparator() : Returns the comparator used to order the keys in the map, or null if the map uses natural ordering.

.

 SortedMap subMap(K fromKey, K toKey) : Returns the entries of the map whose keys are between fromKey and toKey, including fromKey.

.

 SortedMap headMap (K toKey) : Returns the entries whose keys are less than (occur before) the toKey.

.

 SortedMap tailMap(K fromKey) : Returns the entries whose keys are greater than or equal to fromKey.

.

 K firstKey() : Returns the first (lowest) key in the sorted map.

.

 K lastKey() : Returns the last (highest) key in the sorted key.

.

Examples:

1.The example below usage of above methods with a sorted map.

.

.

//create a sorted map
SortedMap<String,Integer> employeeRates = new TreeMap<>();

//add elements
employeeRates.put(“John”,20);
employeeRates.put(“Tom”,15);
employeeRates.put(“Harry”,45);
employeeRates.put(“Anne”,30);
employeeRates.put(“Mira”,25);

System.out.println(“Sorted Map: ” + employeeRates);

//firstKey
System.out.println(“First key: ” + employeeRates.firstKey());

//lastKey
System.out.println(“Last key: ” + employeeRates.lastKey());

//subMap
System.out.println(“SubMap (Harry,Mira): ” + employeeRates.subMap(“Harry”,“Mira”));

//headMap
System.out.println(“HeadMap (Tom): ” + employeeRates.headMap(“Tom”));

//tailMap
System.out.println(“TailMap (Tom): ” + employeeRates.tailMap(“Tom”));

.

Output:

.

Sorted Map: {Anne=30, Harry=45, John=20, Mira=25, Tom=15}

First key: Anne

Last key: Tom

SubMap (Harry,Mira): {Harry=45, John=20}

HeadMap (Tom): {Anne=30, Harry=45, John=20, Mira=25}

TailMap (Tom): {Tom=15}

1.11NavigableMap

.

public interface NavigableMap<K,V> extends SortedMap<K,V>

.

 The NavigableMap interface extends the SortedMap interface.
 It provides additional methods for navigation through the sorted map.
 The NavigableMap can be iterated in ascending or descending order.

The class which implements the NavigableMap interface:

TreeMap

 A NavigableMap implementation based on a TreeMap.

Creating a NavigableMap (using natural ordering):

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

.

Methods

The NavigableMap interface contains the following methods in addition to the methods inherited from the SortedMap interface:

 Map.Entry<K,V> lowerEntry(K key) : Returns the entry associated with the greatest key that is less than the given key.

.

 K lowerKey(K key) : Returns the greatest key that is than the given key.

.

 Map.Entry<K,V> floorEntry(K key) : Returns the entry associated with the greatest key that is less than or equal to the given key.

.

 K floorKey(K key) : Returns the greatest key that is less than or equal to the given key.

.

 Map.Entry<K,V> ceilingEntry(K key) : Returns the entry associated with the least key in the map that is greater than or equal to the given key.

.

 K ceiling(K key) : Returns the least key in the map that is greater than or equal to the given key.

.

 Map.Entry<K,V> higherEntry(K key) : Returns the entry associated with the least key in the map that is greater than the given key.

.

 K higher(K key) : Returns the least key in the map that is greater than the given element.

.

 Map.Entry<K,V> firstEntry() : Returns the entry associated with the least key in the map

.

 Map.Entry<K,V> lastEntry() : Returns the entry associated with the greatest key in the map

.

 Map.Entry<K,V> pollFirstEntry() : Returns and removes the entry associated with the first (lowest) key in the map.

.

 Map.Entry<K,V> pollLastEntry() : Returns and removes the entry associated with the last (highest) key in the map.

.

 NavigableMap<K,V> descendingMap(): Returns a reverse order view of the entries in the map.

.

 NavigableSet<K> navigableKeySet() : Returns as a NavigableSet all the keys contained in the map.

.

 NavigableSet<K> descendingKeySet() : Returns a reverse order NavigableSet of all the keys contained in the map.

.

 NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) : Returns the entries whose keys occur between fromKey and toKey. fromKey and toKey are included in the result based on the value of fromInclusive and toInclusive, respectively.

.

 NavigableMap<K,V> headMap(K toKey, boolean inclusive) : Returns the entries whose keys are less than (or equal to, if inclusive in true) the toKey.

.

 NavigableMap<K,V> tailMap(K fromKey, boolean inclusive) : Returns the entries whose keys are greater than (or equal to, if inclusive is true) the fromKey.

.

Examples:

1.The example below usage of above methods with a navigable map.

//create a map
NavigableMap<String, Integer> employeeRates = new TreeMap<>();

//add elements
employeeRates.put(“John”, 20);
employeeRates.put(“Tom”, 15);
employeeRates.put(“Harry”, 45);
employeeRates.put(“Anne”, 30);
employeeRates.put(“Mira”, 25);

System.out.println(“Navigable Map: ” + employeeRates);

//reverse order
System.out.println(“Map reverse order: ” + employeeRates.descendingMap());

//lower
System.out.println(“lowerKey(Harry): ” + employeeRates.lowerKey(“Harry”));
System.out.println(“lowerEntry(Harry): ” + employeeRates.lowerKey(“Harry”));

//floor
System.out.println(“floorEntry(Harry): ” + employeeRates.floorEntry(“Harry”));

//ceiling
System.out.println(“ceilingEntry(Harry): ” + employeeRates.ceilingEntry(“Harry”));

//higher
System.out.println(“higherEntry(Harry): ” + employeeRates.higherEntry(“Harry”));

//submap
System.out.println(“submap(Anne,John) both excluded: ” + employeeRates.subMap(“Anne”, false, “John”, false));

//headmap
System.out.println(“headMap(John) included: ” + employeeRates.headMap(“John”, true));

//tailmap
System.out.println(“tailmap(John) excluded: ” + employeeRates.tailMap(“John”, false));

//first
System.out.println(“firstEntry: ” + employeeRates.firstEntry());
System.out.println(“poll first: ” + employeeRates.pollFirstEntry() + “; map: ” + employeeRates);

//last
System.out.println(“lastEntry: ” + employeeRates.lastEntry());
System.out.println(“poll last: ” + employeeRates.pollLastEntry() + “; map: ” + employeeRates);

.

Output:

.

Navigable Map: {Anne=30, Harry=45, John=20, Mira=25, Tom=15}

Map reverse order: {Tom=15, Mira=25, John=20, Harry=45, Anne=30}

lowerKey(Harry): Anne

lowerEntry(Harry): Anne

floorEntry(Harry): Harry=45

ceilingEntry(Harry): Harry=45

higherEntry(Harry): John=20

submap(Anne,John) both excluded: {Harry=45}

headMap(John) included: {Anne=30, Harry=45, John=20}

tailmap(John) excluded: {Mira=25, Tom=15}

firstEntry: Anne=30

poll first: Anne=30; map: {Harry=45, John=20, Mira=25, Tom=15}

lastEntry: Tom=15

poll last: Tom=15; map: {Harry=45, John=20, Mira=25}

.

.

1.12Iterator

.

public interface Iterator<E>

.

 Iterator is used to iterate over the elements in the collection.
 It allows the caller to remove the elements in the collection during iteration.
 It can be used to iterate only in the forward direction.

Obtaining an Iterator from a Collection:

iterator() method is used to obtain an iterator from a Collection.

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

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

.

Methods

Following are the methods provided by the Iterator interface.

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

.

 E next() : Returns the next element in the iteration.

.

 void remove() : Removes from the underlying collection the last element returned by the iterator.

.

 void forEachRemaining(Consumer<? Super E> action) : Performs the given action for each remaining element until all elements have been processed.

Examples

1.The example below usage of an iterator with a list.

//create a list
List<String> names = new ArrayList<>(Arrays.asList(
“John”,
“Tom”,
“Anne”,
“Harry”,
“Jack”
));
System.out.println(“List: ” + names);

//get an iterator
Iterator<String> iterator = names.iterator();

//iterate
while(iterator.hasNext()) //until all elements are iterated
{
//get next element
String name = iterator.next();
System.out.println(“Name: ” + name);

//remove
if(name.startsWith(“J”))
{

iterator.remove();

System.out.println(name + ” removed.”);
}

}

System.out.println(“List: ” + names);

//start iterator again
iterator = names.iterator();

//forEachRemaining
iterator.forEachRemaining(
s -> {
System.out.println(s.toUpperCase());}
);

.

Output:

.

List: [John, Tom, Anne, Harry, Jack]

Name: John

John removed.

Name: Tom

Name: Anne

Name: Harry

Name: Jack

Jack removed.

List: [Tom, Anne, Harry]

TOM

ANNE

HARRY

.

.

1.13ListIterator

public interface ListIterator<E> extends Iterator<E>

.

 The ListIterator interface extends the Iterator interface.
 ListIterator can be used to iterate a list in both forward and backward direction.
 It allows to modify the list during iteration, and obtain the current position of iterator.
 It can be used to iterate only in the forward direction.

Obtaining a ListIterator from a List:

listIterator() method is used to obtain an iterator from a list.

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

ListIterator<String> listIterator = list.listIterator();

.

Methods

Following are the methods provided by the ListIterator interface.

 boolean hasNext() : Returns true if the list has more elements when traversing the list in the forward direction.

.

 E next() : Returns the next element in the list and moves the cursor position forward.

.

 boolean hasPrevious() : Returns true if the list has more elements when traversing the list in the backward direction.

.

 E previous() : Returns the previous element in the list and moves the cursor position backwards.
 int nextIndex() : Returns the index of the element that would be returned by next().

.

 int previousIndex() : Returns the index of the element that would be returned by previous().

.

 void remove() : Removes from the list the last element that was returned by next() or previous().

.

 void set(E e) : Replaces the last element returned by next() or previous() with the given element.

.

 void add(E e) : Inserts the given element into the list, before the element that would be returned by next().

Examples

1.The example below usage of a ListIterator with a list.

//create a list
List<String> names = new ArrayList<>(Arrays.asList(
“John”,
“Tom”,
“Anne”,
“Harry”,
“Jack”
));
System.out.println(“List: ” + names);

//get an iterator
ListIterator<String> iterator = names.listIterator();

//next
System.out.println(“Next element: ” + iterator.next());

//next index
System.out.println(“Next index: ” + iterator.nextIndex());

//add
iterator.add(“Ankit”);
System.out.println(“Add(Ankit): ” + names);

//set
System.out.println(“Next element: ” + iterator.next());
iterator.set(“Nilton”);
System.out.println(“Set(Nilton): ” + names);

//hasNext
while(iterator.hasNext())
{

System.out.println(“Next element: ” + iterator.next());
}

//previous
while(iterator.hasPrevious())
{

System.out.println(“Previous element: ” + iterator.previous());
}

.

Output:

.

List: [John, Tom, Anne, Harry, Jack]

Next element: John

Next index: 1

Add(Ankit): [John, Ankit, Tom, Anne, Harry, Jack]

Next element: Tom

Set(Nilton): [John, Ankit, Nilton, Anne, Harry, Jack]

Next element: Anne

Next element: Harry

Next element: Jack

Previous element: Jack

Previous element: Harry

Previous element: Anne

Previous element: Nilton

Previous element: Ankit

Previous element: John

.

.

4.Time Complexity – Basic Operations

.

Following are the time complexities of basic operations on the different implementations in Collections framework.

List

Implementation

add

remove

contains

get

next

ArrayList

O(1)

O(n)

O(n)

O(1)

O(1)

LinkedList

O(1)

O(1)

O(n)

O(n)

O(1)

.

Set

Implementation

add

remove

contains

get

next

HashSet

O(1)

O(1)

O(1)

O(1)

O(h/n)

LinkedHashSet

O(1)

O(1)

O(1)

O(1)

O(1)

TreeSet

O(log n)

O(log n)

O(log n)

O(log n)

O(log n)

.

Map

Implementation

Add

remove

contains

get

next

HashMap

O(1)

O(1)

O(1)

O(1)

O(h/n)

LinkedHashMap

O(1)

O(1)

O(1)

O(1)

O(1)

TreeMap

O(log n)

O(log n)

O(log n)

O(log n)

O(log n)

.

Queue

Implementation

offer

peek

poll

LinkedList (Queue)

O(1)

O(1)

O(1)

PriorityQueue

O(log n)

O(1)

O(log n)

.

5.Collections class

.

The Collections class provides utility (static) methods to perform operations on collections.

Following are some of the important methods:

 addAll(Collection<T> c, T.. elements) : Adds all of the given elements to the given collection.

.

 sort(List<T> list) : Sorts the given list into ascending order according to the natural ordering of its elements. All elements in the list must implement the Comparable interface.

.

 binarySearch(List<T> list, T key) : Searches the given (sorted) list for the given object using the binary search algorithm.

.

 reverse(List<T> list) : Reverses the order of the elements in the given list.

.

 shuffle(List<T> list) : Randomly shuffles the given list.

.

 swap( List<T> list, int i , int j) : Swaps the elements at the given positions in the given list.

.

 fill(List<T>, T obj) : Replaces all elements of the given list with the given element.

.

 copy(List<T> dest, List<T> src) : Copies all elements from one list to another.

.

 min(Collection<T> c) : Returns the minimum element of the given collection according to natural ordering of its elements.

.

 max(Collection<T> c) : Returns the maximum element of the given collection according to natural ordering of its elements.

.

 replaceAll(List<T> list, T oldVal, T newVal) : Replaces all occurrences of given oldVal with the newVal in a list.

.

 unmodifiableCollection(Collection<T> c) : Returns an immutable (read-only) view of the given collection. There are more variations of this method.

.

Examples

1.The example below shows usage of above methods with a list.

//create a list
List<String> names = new ArrayList<>();
System.out.println(“List: ” + names);

//add all
Collections.addAll(names, “John”, “Tom”, “Anne”, “Harry”, “Jack”);
System.out.println(“Add all: ” + names);

//sort
Collections.sort(names);
System.out.println(“Sort: ” + names);

//search
int index = Collections.binarySearch(names, “Tom”);
System.out.println(“Search(Tom), index: ” + index);

//reverse
Collections.reverse(names);
System.out.println(“Reverse: ” + names);

//shuffle
Collections.shuffle(names);
System.out.println(“Shuffle: ” + names);

//swap
Collections.swap(names, 1, 3);
System.out.println(“swap(1,3): ” + names);

//copy
List<String> namesNew = new ArrayList<>(Arrays.asList(
“Ankit”,
“Nilton”
));
Collections.copy(names, namesNew);
System.out.println(“copy(Ankit,Nilton): ” + names);

//min
System.out.println(“min: ” + Collections.min(names));
.

//max
System.out.println(“max: ” + Collections.max(names));

.

Output:

.

List: []

Add all: [John, Tom, Anne, Harry, Jack]

Sort: [Anne, Harry, Jack, John, Tom]

Search(Tom), index: 4

Reverse: [Tom, John, Jack, Harry, Anne]

Shuffle: [Harry, John, Tom, Anne, Jack]

swap(1,3): [Harry, Anne, Tom, John, Jack]

copy(Ankit,Nilton): [Ankit, Nilton, Tom, John, Jack]

min: Ankit

max: Tom

.

.

6.Properties class

.

 The Properties class represents a persistent set of properties, like a Map of String key and value pairs.
 Each property is a set of a String key and its corresponding String value.
 The Properties can be saved to a stream or loaded from a stream.
 The Properties class provides methods to get properties from and store properties into a file on the file system.
 This class is used to manage configuration properties for applications.

Creating a Properties instance:

Properties props = new Properties();

.

Methods

Following are some of the important methods:

 void load(Reader r) : Load the properties from given Reader object
 void load(InputStream in) : Load the properties from given InputStream object
 void loadFromXml(InputStream in) : Loads the properties from an XML document on the given input stream.
 String getProperty(String key) : Returns value for the given key.
 String getProperty(String key, String defaultValue) : Returns the value for the given key, and the defaultValue if no value is found.
 Void setProperty(String key, String value) : Puts the given value against the given key.
 Void store(Writer r, String comment) : Writes the properties in the given writer object.
 Void store(OutputStream o, String comment) : Writes the properties in the given output stream object.
 Void storeToXML(OutputStream o, String comment) : Writes the properties into an XML file.

.

Examples

1.The example below shows how to store properties into a file “app.properties”.

Properties props = new Properties();

props.setProperty(“application.name”, “collections-demo”);
props.setProperty(“application.version”, “1.0”);
props.setProperty(“environment”, “demo”);

try
{

//store into a file
FileWriter fw = new FileWriter(/data/app.properties”);
props.store(fw, “properties file”);

.

}
catch(Exception e)
{

e.printStackTrace();

}

.

File ‘app.properties’ is created at the given location with the following content:

.

#properties file
#Sun Apr 18 19:52:09 IST 2021

environment=demo
application.version=1.0
application.name=collections-demo

.

.

.

2.The example below shows how to load properties from the file created in previous example.

Properties props = new Properties();

try
{
FileReader fw = new FileReader(/data/app.properties”);
props.load(fw);

//get property
System.out.println(“Application name = ” + props.getProperty(“application.name”));
System.out.println(“Application version = ” + props.getProperty(“application.version”));
System.out.println(“Environment = ” + props.getProperty(“environment”));

}

catch(Exception e)
{

e.printStackTrace();

}

.

.

Output

.

Application name = collections-demo

Application version = 1.0

Environment = demo

.

.

.

7.Equals() and hashCode()

.

 The Object class defines both the equals() and hashCode() methods – so these methods are implicitly defined in each class
 These methods are used in contract for checking equality of objects

.

equals()

boolean equals(Object obj)

 This method returns true if the invoking object is equal to the given object.
 In collections, this method is used to while performing operations on values, to match a given value.
 We need to override equals() in our (user-defined) class to ensure correct comparison of objects.

.

Examples:

1.The example below shows the (default implementation) usage of String.equals() to compare Strings.

String name1 = “Ankit”;
String name2 = “Nilton”;
String name3 = “Ankit”;

System.out.println(“name1 equals name2 : ” + name1.equals(name2));
System.out.println(“name1 equals name3 : ” + name1.equals(name3));

.

.

Output

.

name1 equals name2 : false

name1 equals name3 : true

.

.

.

2.The example below shows the usage of equals() in user-defined class; for comparing Employee objects.

.

//POJO class

public class Employee {
private String name;
private Integer hourRate;
public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Integer getHourRate() {
return hourRate;
}

public void setHourRate(Integer hourRate) {
this.hourRate = hourRate;
}

public Employee(String name, Integer hourRate) {
super();
this.name = name;
this.hourRate = hourRate;
}

@Override
public String toString() {
return “Employee [name=” + name + “, hourRate=” + hourRate + “]”;
}

}

.

.

Without defining how the Employee objects should be checked for equality, we do not get the correct results. Though employee1 and employee3 have the same field values, they are not considered equals as they are two different objects (references) .

Employee employee1 = new Employee(“Ankit”, 20);
Employee employee2 = new Employee(“Ankit”, 20);
Employee employee3 = new Employee(“Ankit”, 30);

System.out.println(“employee1 equals employee2: ” + employee1.equals(employee2));
.

System.out.println(“employee1 equals employee3: ” + employee1.equals(employee3));

.

.

Output

.

employee1 equals employee2: false

employee1 equals employee3: false

.

We can define how Employee objects should be checked for equality i.e. override the equals() method in the Employee class and provide logic for equality.

.

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Employee employee = (Employee) o;
return name.equals(employee.name) && hourRate.equals(employee.hourRate);
}

.

Now, the equality will be checked on basis of the logic defined above in the equals() method i.e. name and hourRate should be equal.

Employee employee1 = new Employee(“Ankit”, 20);
Employee employee2 = new Employee(“Ankit”, 20);
Employee employee3 = new Employee(“Ankit”, 30);

System.out.println(“employee1 equals employee2: ” + employee1.equals(employee2));
.

System.out.println(“employee1 equals employee3: ” + employee1.equals(employee3));

.

.

Output

.

employee1 equals employee2: true

employee1 equals employee3: false

.

hashcode()

int hashCode()

 This method is used while working with keys in a hashtable (hashmap or hashset).
 It returns an integer value called hashcode which is used to determine the storage area (bucket) of a key while inserting or retrieving an object in a hashtable.

hashcode() and equals() contract

 Two objects could have the same hash code and so two keys could be stored in the same bucket. Here, equals() would be used to match the given key and then return the associated value.
  If two objects are equals according to the equals() method, then they must have the same hash code. So hashcode() should be overridden if we override the equals() method.
 If two objects have the same hash code, they may or may not be equal.

.

Examples:

1.The example below shows an overridden hashcode method in the Employee class.

.

@Override
public int hashCode() {
return name.length() * hourRate.hashCode();
}

.

.

8.Sorting

.

For sorting or comparing the collections, the classes must implement the Comparable interface.

The String class and the wrapper classes implement the Comparable interface, and so they can be sorted or compared on the basis of their natural order.

For our own (user-defined) classes we need to implement Comparable interface and override compareTo() method to define the comparison logic.

Comparable Interface

public interface Comparable<T>

{

  int compareTo(T o);

}

.

The compareTo() method compares the given object to the current object and returns a negative value, zero or a positive value if current object is smaller than, equal to, or greater than the given object, respectively.

.

Examples

.

1.The example below shows how to sort the Employee objects on the basis of the hourRates.

.

//POJO class

public class Employee implements Comparable<Employee> {
private String name;
private Integer hourRate;
public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Integer getHourRate() {
return hourRate;
}

public void setHourRate(Integer hourRate) {
this.hourRate = hourRate;
}

public Employee(String name, Integer hourRate) {
super();
this.name = name;
this.hourRate = hourRate;
}

@Override
public String toString() {
return “Employee [name=” + name + “, hourRate=” + hourRate + “]”;
}


@Override
public int compareTo(Employee o) {
return this.hourRate.compareTo(o.hourRate);
}

}

.

.

.

Comparator Interface

.

public interface Comparator<T>

{

  int compare(T o1, T o2);

}

.

The Comparator interface is used to compare and sort two objects. The objects are not required to implement the Comparable interface.

The compare() method compares the first object to the second object and returns a negative value, zero or a positive value if first object is smaller than, equal to, or greater than the second object, respectively.

.

.

Examples

.

1.The example below shows how to create a comparator for the Employee objects on the basis of the hourRates.

.

Comparator<Employee> employeeComparator = new Comparator<Employee>() {
@Override
public int compare(Employee o1, Employee o2) {
o1.
hourRate.compareTo(o2.hourRate);
}

};

.

.

.

Previous

Leave a Reply

Your email address will not be published. Required fields are marked *

Working Hours

  • Monday 9am - 6pm
  • Tuesday 9am - 6pm
  • Wednesday 9am - 6pm
  • Thursday 9am - 6pm
  • Friday 9am - 6pm
  • Saturday Closed
  • Sunday Closed