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

5.collections in Java

Uploaded by

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

5.collections in Java

Uploaded by

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

We are on a mission to address the digital

skills gap for 10 Million+ young professionals,


train and empower them to forge a career
path into future tech
Collections in Java

13 DECEMBER ‘2022
Collections in Java

Collections - Introduction

• The Java Collections Framework standardizes the way in which groups of objects are handled by

your programs

• Java provided ad hoc classes such as Dictionary, Vector, Stack and Properties to store and

manipulate groups of objects

3 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

Collections - Introduction

• The Collections Framework was designed to meet several goals.

• First, the framework had to be high-performance. The implementations for the fundamental

collections (dynamic arrays, linked lists, trees, and hash tables) are highly efficient.

• Second, the framework had to allow different types of collections to work in a similar manner and with

a high degree of interoperability.

• Third, extending and/or adapting a collection had to be easy.

4 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

Hierarchy of Collection Framework

5 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

Collections Interface

• The Collections Framework defines several core interfaces

6 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

Collections Interfaces

• In addition to the collection interfaces, collections also use the Comparator, RandomAccess,

Iterator, ListIterator, and Spliterator interfaces.

• Comparator defines how two objects are compared.

• Iterator, ListIterator and Spliterator enumerate the objects within a collection.

• By implementing RandomAccess, a list indicates that it supports efficient, random access to its

elements.

7 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

Collections Interfaces

• To provide the greatest flexibility in their use, the collection interfaces allow some methods to be

optional.

• The optional methods enable you to modify the contents of a collection.

• Collections that support these methods are called modifiable.

• Collections that do not allow their contents to be changed are called unmodifiable.

• If an attempt is made to use one of these methods on an unmodifiable collection, an

UnsupportedOperationException is thrown.

8 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Collection Interfaces

• The Collection interface is the foundation upon which the Collections Framework is built because it

must be implemented by any class that defines a collection.

• Collection is a generic interface that has this declaration:

interface Collection<E>

Here, E specifies the type of objects that the collection will hold.

• Collection extends the Iterable interface.

9 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Collection Interface

• Collection declares the core methods that all collections will have. These methods are

10 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Collection Interface

11 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The List Interface

• The List interface extends Collection and declares the behavior of a collection that stores a

sequence of elements.

• Elements can be inserted or accessed by their position in the list, using a zero-based index.

• A list may contain duplicate elements.

• List is a generic interface that has this declaration:

interface List<E>

Here, E specifies the type of objects that the list will hold.

• In addition to the methods defined by Collection, List defines some of its own

12 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The List Interface

13 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The List Interface

• In addition to the methods defined by Collection, List defines some of its own

14 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The List Interface

15 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The ArrayList Class

• The ArrayList class extends AbstractList and implements the List interface.

• ArrayList is a generic class that has this declaration:

class ArrayList<E>

Here, E specifies the type of objects that the list will hold.

• ArrayList supports dynamic arrays that can grow as needed.

• In Java, standard arrays are of a fixed length. After arrays are created, they cannot grow or shrink,

which means that you must know in advance how many elements an array will hold.

• The Collections Framework defines ArrayList which is a variable-length array of object references.

That is, an ArrayList can dynamically increase or decrease in size


16 Collections in Java | © SmartCliff | Internal | Version 1.0
Collections in Java

The Array List Class– Example #1

/*This example demonstrate the ArrayList Classes*/


import java.util.*;
public class ArrayListDemo {
public static void main(String args[]) {
//Create an Arraylist
ArrayList <String> Arr = new ArrayList<String>();
System.out.println("Initial Size of Array List is "+Arr.size());
Arr.add("C");
Arr.add("A");
Arr.add("E");
Arr.add("B");
Arr.add("D");
Arr.add("F");
Arr.add(1, "G");
System.out.println("After Insert the Size of Array List is "+Arr.size());
17 Collections in Java | © SmartCliff | Internal | Version 1.0
Collections in Java

The Array List Class– Example #1

System.out.println("Contents of ArrayList "+Arr);


//Remove Element from array List
Arr.remove("F");
Arr.remove(2); Output:
System.out.println("Contents of ArrayList "+Arr);
Initial Size of Array List is 0
}
After Insert the Size of Array List is 7
}
Contents of ArrayList [C, G, A, E, B,
D, F]
Contents of ArrayList [C, G, E, B, D]

18 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Array List Class– Example #2

/*This example demonstrate the ArrayList Classes*/


import java.util.*;

public class ArrayListDemo {


public static void main(String args[]) {
//Create an Arraylist
ArrayList <Integer> Arr = new ArrayList<Integer>();
System.out.println("Initial Size of Array List is "+Arr.size());
Arr.add(1);
Arr.add(2);
Arr.add(3);
Arr.add(4);
System.out.println("After Insert the Size of Array List is "+Arr.size());
System.out.println("Contents of ArrayList "+Arr);
19 Collections in Java | © SmartCliff | Internal | Version 1.0
Collections in Java

The Array List Class– Example #2

Integer ia[] = new Integer[Arr.size()];


ia = Arr.toArray(ia);
int sum = 0;
for(int i:ia) { Output:
sum+=i; Initial Size of Array List is 0
} After Insert the Size of Array List is
System.out.println("Sum value is "+sum); 4
} Contents of ArrayList [1, 2, 3, 4]
} Sum value is 10

20 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The LinkedList Class

• The LinkedList class extends AbstractSequentialList and implements the List, Deque, and Queue
interfaces.

• It provides a linked-list data structure.

• LinkedList is a generic class that has this declaration:

class LinkedList<E>

Here, E specifies the type of objects that the list will hold.

LinkedList has the two constructors shown here:

• LinkedList() - builds an empty linked list

• LinkedList(Collection<? extends E> c) – builds a linked list that is initialized with the elements of
the collection c

• LinkedList also implements the Deque interface

21 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Linked List Class– Example #1

/*This example demonstrate the LinkedList Classes*/


import java.util.*;
public class LinkedListDemo01 {
public static void main(String args[]) {
//Create an Arraylist
LinkedList <String> Arr = new LinkedList<String>();
System.out.println("Initial Size of LinkedList is "+Arr.size());
Arr.add("C");
Arr.add("A");
Arr.add("E");
Arr.add("B");
Arr.add("D");
Arr.addFirst("F");
Arr.addLast("G");
System.out.println("After Insert the Size of LinkedList is "+Arr.size());
22 Collections in Java | © SmartCliff | Internal | Version 1.0
Collections in Java

The Linked List Class– Example #1

System.out.println("Contents of LinkedList "+Arr);


//Remove Element from array List
Arr.remove(“E");
Arr.removeFirst(2);
System.out.println("Contents of LinkedList "+Arr);
}
} Output:
Initial Size of LinkedList is 0
After Insert the Size of LinkedList is 7
Contents of LinkedList [F, C, A, E, B, D, G]
Contents of LinkedList [C, A, B, D, G]

23 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Vector Class

• Vector uses a dynamic array to store the data elements.

• It is similar to ArrayList.

• It is synchronized and contains many methods that are not the part of Collection framework.

24 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Vector Class– Example #1

/*This example demonstrate the Vector Class*/


import java.util.*;

public class VectorDemo {


public static void main(String args[]){
Vector<String> v=new Vector<String>();
System.out.println("Size of the vector is "+v.size());
v.add("A");
v.add("B");
v.add("C");
v.add("D");
System.out.println("Elements in the vector "+v);
System.out.println("Size of the vector is "+v.size());
25 Collections in Java | © SmartCliff | Internal | Version 1.0
Collections in Java

The Vector Class– Example #1

v.remove("A");
System.out.println("Elements in the vector after remove "+v);
System.out.println("Size of the vector after the removal is "+v.size());
}
}
Output:
Size of the vector is 0
Elements in the vector [A, B, C, D]
Size of the vector is 4
Elements in the vector after remove [B, C, D]
Size of the vector after the removal is 3

26 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Stack Class

• The stack is the subclass of Vector.

• It implements the last-in-first-out data structure, i.e., Stack.

• The stack contains all of the methods of Vector class and also provides its methods like boolean

push(), boolean peek(), boolean push(object o) which defines its properties.

27 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Stack Class– Example #1


/*This example demonstrate the Stack Class*/
import java.util.*;

public class StackDemo {


public static void main(String args[]){
Stack<String> stk=new Stack<String>();
System.out.println("Size of the stack is "+stk.size());
stk.push("A");
stk.push("B");
stk.push("C");
stk.push("D");
System.out.println("Elements in the stack "+stk);
System.out.println("Size of the stack is "+stk.size());
stk.pop();

28 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Stack Class– Example #1

System.out.println("Elements in the stack after remove "+stk);


System.out.println("Size of the stack after the removal is "+stk.size());
}
}
Output:
Size of the stack is 0
Elements in the stack [A, B, C, D]
Size of the stack is 4
Elements in the stack after remove [A, B, C]
Size of the stack after the removal is 3

29 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Set Interface

• The Set interface defines a set.

• It extends Collection and specifies the behavior of a collection that does not allow duplicate

elements.

• The add( ) method returns false if an attempt is made to add duplicate elements to a set.

• With two exceptions, it does not specify any additional methods of its own.

• Set is a generic interface that has this declaration:

interface Set<E>

Here, E specifies the type of objects that the set will hold.

30 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Set Interface

31 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The HashSet Class

• HashSet extends AbstractSet and implements the Set interface.

• It creates a collection that uses a hash table for storage.

• HashSet is a generic class that has this declaration:

class HashSet<E>

Here, E specifies the type of objects that the set will hold.

• In hashing, the informational content of a key is used to determine a unique value, called its hash

code.

• HashSet does not define any additional methods beyond those provided by its superclasses and

interfaces.
32 Collections in Java | © SmartCliff | Internal | Version 1.0
Collections in Java

The HashSet Class– Example #1


/*This example demonstrate the Stack Class*/
import java.util.*;
public class HashSetDemo {
public static void main(String args[]){
HashSet<String> hs=new HashSet<String>();
System.out.println("Size of the HashSet is "+hs.size());
//adding elements
hs.add("Alpha");
hs.add("Beta");
hs.add("Gamma");
hs.add("Epsilon");
hs.add("Eta");
hs.add("Omega");
System.out.println("Elements in the HashSet "+hs);
System.out.println("Size of the HashSet is "+hs.size());

33 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The HashSet Class– Example #1

hs.remove("Eta");
System.out.println("Elements in the HashSet after remove "+hs);
System.out.println("Size of the HashSet after the removal is "+hs.size());
}
}

Output:
Size of the HashSet is 0
Elements in the HashSet [Gamma, Eta, Alpha, Epsilon, Omega, Beta]
Size of the HashSet is 6
Elements in the HashSet after remove [Gamma, Alpha, Epsilon, Omega, Beta]
Size of the HashSet after the removal is 5

34 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The LinkedHashSet Class

• The LinkedHashSet class extends HashSet and adds no members of its own.

• It is a generic class that has this declaration:

class LinkedHashSet<E>

Here, E specifies the type of objects that the set will hold.

• Its constructors parallel those in HashSet.

• LinkedHashSet maintains a linked list of the entries in the set, in the order in which they were

inserted.

35 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The LinkedHashSet Class– Example #1


/*This example demonstrate the Stack Class*/
import java.util.*;

public class LinkedHashSetDemo01 {


public static void main(String args[]){
LinkedHashSet<String> hs=new LinkedHashSet<String>();
System.out.println("Size of the LinkedHashSet is "+hs.size());
//adding elements
hs.add("Alpha");
hs.add("Beta");
hs.add("Gamma");
hs.add("Epsilon");
hs.add("Eta");
hs.add("Omega");
System.out.println("Elements in the LinkedHashSet "+hs);

36 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The LinkedHashSet Class– Example #1


System.out.println("Size of the LinkedHashSet is "+hs.size());
hs.remove("Eta");
System.out.println("Elements in the LinkedHashSet after remove "+hs);
System.out.println("Size of the LinkedHashSet after the removal is "+hs.size());
}
}

Output:
Size of the LinkedHashSet is 0
Elements in the LinkedHashSet [Alpha, Beta ,Gamma, Epsilon, Eta ,Omega]
Size of the LinkedHashSet is 6
Elements in the LinkedHashSet after remove [Alpha, Beta ,Gamma, Epsilon, Omega]
Size of the LinkedHashSet after the removal is 5

37 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Sorted Set Interface

• The SortedSet interface extends Set and declares the behavior of a set sorted in ascending order.

• SortedSet is a generic interface that has this declaration:

interface SortedSet<E>

Here, E specifies the type of objects that the set will hold.

• In addition to those methods provided by Set, the SortedSet interface declares the methods

summarized

38 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Sorted Set Interface

39 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Sorted Set Interface

• In addition to the methods defined by Collection, Sorted Set defines some of its own

40 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The NavigableSet Interface

• The NavigableSet interface extends SortedSet and declares the behavior of a

• collection that supports the retrieval of elements based on the closest match to

• a given value or values.

• NavigableSet is a generic interface that has this declaration:

interface NavigableSet<E>

Here, E specifies the type of objects that the set will hold. In addition to the

41 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The NavigableSet Interface

42 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Navigable Set Interface

• Methods that it inherits from SortedSet, NavigableSet adds those summarized

43 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Navigable Set Interface

44 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The TreeSet Class

• TreeSet extends AbstractSet and implements the NavigableSet interface.

• It creates a collection that uses a tree for storage.

• Objects are stored in sorted, ascending order.

• Access and retrieval times are quite fast, which makes TreeSet an excellent choice when storing
large amounts of sorted information that must be found quickly.

• TreeSet is a generic class that has this declaration:

class TreeSet<E>

Here, E specifies the type of objects that the set will hold.

45 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The TreeSet Class– Example #1

/*This example demonstrate the TreeSet Class*/


import java.util.*;

public class TreeSetDemo {


public static void main(String args[]){
TreeSet<String> Ts=new TreeSet<String>();
System.out.println("Size of the TreeSet is "+Ts.size());
//adding elements
Ts.add("C");
Ts.add("B");
Ts.add("A");
Ts.add("E");
Ts.add("F");
Ts.add("D");
System.out.println("Elements in the TreeSet "+Ts);

46 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The LinkedHashSet Class– Example #1

System.out.println("Size of the TreeSet is "+Ts.size());


Ts.remove("E");
System.out.println("Elements in the TreeSet after remove "+Ts);
System.out.println("Size of the TreeSet after the removal is "+Ts.size());
}
} Output:
Size of the TreeSet is 0
Elements in the TreeSet [A, B, C, D, E, F]
Size of the TreeSet is 6
Elements in the TreeSet after remove [A, B, C, D, F]
Size of the TreeSet after the removal is 5

47 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Queue Interface

• The Queue interface extends Collection and declares the behavior of a queue, which is often a first-

in, first-out list.

• There are types of queues in which the ordering is based upon other criteria. Queue is a generic

interface that has this declaration:

interface Queue<E>

Here, E specifies the type of objects that the queue will hold.

48 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Queue Interface

49 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Queue Interface

• The methods declared by Queue are

50 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Priority Queue Class

• PriorityQueue extends AbstractQueue and implements the Queue interface.

• It creates a queue that is prioritized based on the queue’s comparator.

• PriorityQueue is a generic class that has this declaration:

class PriorityQueue<E>

Here, E specifies the type of objects stored in the queue.

• PriorityQueues are dynamic, growing as necessary.

51 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Priority Queue Class– Example #1

/*This example demonstrate the PriorityQueue Class*/


import java.util.*;

public class PriorityQueueDemo {


public static void main(String args[]){
PriorityQueue<String> pq=new PriorityQueue<String>();
System.out.println("Size of the PriorityQueue is "+pq.size());
//adding elements
pq.add("C");
pq.add("B");
pq.add("A");
pq.add("E");
pq.add("F");
pq.add("D");
System.out.println("Elements in the PriorityQueue "+pq);

52 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Priority Queue Class– Example #1

System.out.println("Size of the PriorityQueue is "+pq.size());


pq.remove("E");
pq.poll();
System.out.println("Elements in the PriorityQueue after remove "+pq);
System.out.println("Size of the PriorityQueue after the removal is "+pq.size());
} Output:
} Size of the PriorityQueue is 0
Elements in the PriorityQueue [A, C, B, E, F, D]
Size of the PriorityQueue is 6
Elements in the PriorityQueue after remove [B, C, F, D]
Size of the PriorityQueue after the removal is 4

53 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The DeQue Interface

• The Deque interface extends Queue and declares the behavior of a doubleended queue.

• Double-ended queues can function as standard, first-in, first-out queues or as last-in, first-out stacks.

• Deque is a generic interface that has this declaration:

interface Deque<E>

Here, E specifies the type of objects that the deque will hold.

54 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The DeQue Interface

55 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The DeQue Interface

• In addition to the methods that it inherits from Queue, Deque adds those methods summarized

56 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The DeQue Interface

57 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Array DeQue Class

• The ArrayDeque class extends AbstractCollection and implements the Deque interface.

• It adds no methods of its own.

• ArrayDeque creates a dynamic array and has no capacity restrictions.

• ArrayDeque is a generic class that has this declaration:

class ArrayDeque<E>

Here, E specifies the type of objects stored in the collection.

58 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Array Deque Class– Example #1

/*This example demonstrate the ArrayDeque Class*/


import java.util.*;

public class ArrayDequeDemo01 {


public static void main(String args[]){
ArrayDeque<String> ad=new ArrayDeque<String>();
System.out.println("Size of the ArrayDeque is "+ad.size());
ad.push("A");
ad.push("B");
ad.push("C");
ad.push("D");
System.out.println("Elements in the ArrayDeque "+ad);
System.out.println("Size of the ArrayDeque is "+ad.size());

59 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Priority Queue Class– Example #1

ad.pop();
System.out.println("Elements in the ArrayDeque after remove "+ad);
System.out.println("Size of the ArrayDeque after the removal is "+ad.size());
}
}

Output:
Size of the ArrayDeque is 0
Elements in the ArrayDeque [D, C, B, A]
Size of the ArrayDeque is 4
Elements in the ArrayDeque after remove [C, B, A]
Size of the ArrayDeque after the removal is 3

60 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Map Interface

• The Map interface maps unique keys to values.

• A key is an object that you use to retrieve a value at a later date. Given a key and a value, you can

store the value in a Map object.

• After the value is stored, you can retrieve it by using its key.

• Map is generic and is declared as shown here:

interface Map<K, V>

Here, K specifies the type of keys, and V specifies the type of values.

61 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Map Interface

• The methods declared by Map are summarized

62 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Map Interface

63 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Map Interface

64 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Map Hierarchy

65 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The HashMap Class

• The HashMap class extends AbstractMap and implements the Map interface.

• It uses a hash table to store the map.

• This allows the execution time of get( ) and put( ) to remain constant even for large sets.

• HashMap is a generic class that has this declaration:

class HashMap<K, V>

Here, K specifies the type of keys, and V specifies the type of values

66 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Hash Map Class – Example #1

/*This example demonstrate the HashMap Class*/


import java.util.*;

public class HashMapDemo {


public static void main(String args[]){
HashMap<String, Double> tm = new HashMap<String, Double>();
System.out.println("Size of the HashMap is "+tm.size());
tm.put("John Doe", 4343.43);
tm.put("Tom Smith",145.23);
tm.put("Jane Baker", 1450.78);
tm.put("Ralph Smith",-18.76);
System.out.println("Elements in the HashMap "+tm);
System.out.println("Size of the HashMap is "+tm.size());
Set<Map.Entry<String, Double>> set = tm.entrySet();

67 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Hash Map Class– Example #1

for(Map.Entry<String, Double> me:set) {


System.out.print(me.getKey()+":");
Output:
System.out.println(me.getValue());
Size of the HashMap is 0
}
Elements in the HashMap {John
}
Doe=4343.43, Ralph Smith=-18.76, Tom
}
Smith=145.23, Jane Baker=1450.78}
Size of the HashMap is 4
John Doe:4343.43
Ralph Smith:-18.76
Tom Smith:145.23
Jane Baker:1450.78

68 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Linked HashMap Class

• LinkedHashMap extends HashMap.

• It maintains a linked list of the entries in the map, in the order in which they were inserted.

• When iterating through a collection-view of a LinkedHashMap, the elements will be returned in the
order in which they were inserted.

• You can also create a LinkedHashMap that returns its elements in the order in which they were last
accessed.

• LinkedHashMap is a generic class that has this declaration:

class LinkedHashMap<K, V>

Here, K specifies the type of keys, and V specifies the type of values.

69 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Linked Hash Map Class – Example #1

/*This example demonstrate the LinkedHashMap Class*/


import java.util.*;

public class LinkedHashMapDemo {


public static void main(String args[]){
LinkedHashMap<String, Double> lhm = new LinkedHashMap<String, Double>();
System.out.println("Size of the LinkedHashMap is "+lhm.size());
lhm.put("John Doe", 4343.43);
lhm.put("Tom Smith",145.23);
lhm.put("Jane Baker", 1450.78);
lhm.put("Ralph Smith",-18.76);
System.out.println("Elements in the LinkedHashMap "+lhm);
System.out.println("Size of the LinkedHashMap is "+lhm.size());
Set<Map.Entry<String, Double>> set = lhm.entrySet();

70 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Hash Map Class– Example #1

for(Map.Entry<String, Double> me:set) {


System.out.print(me.getKey()+":");
Output:
System.out.println(me.getValue());
Size of the LinkedHashMap is 0
}
Elements in the LinkedHashMap {John
}
Doe=4343.43, Tom Smith=145.23, Jane
}
Baker=1450.78, Ralph Smith=-18.76}
Size of the LinkedHashMap is 4
John Doe:4343.43
Tom Smith:145.23
Jane Baker:1450.78
Ralph Smith:-18.76

71 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Sorted Map Interface

• The SortedMap interface extends Map.

• It ensures that the entries are maintained in ascending order based on the keys.

• SortedMap is generic and is declared as shown here:

interface SortedMap<K, V>

Here, K specifies the type of keys, and V specifies the type of values.

72 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Sorted Map Interface

• The methods declared by Sorted Map are summarized

73 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Tree Map Class

• The TreeMap class extends AbstractMap and implements the NavigableMap interface.

• It creates maps stored in a tree structure.

• A TreeMap provides an efficient means of storing key/value pairs in sorted order and allows rapid

retrieval.

• Unlike a hash map, a tree map guarantees that its elements will be sorted in ascending key order.

• TreeMap is a generic class that has this declaration:

class TreeMap<K, V>

Here, K specifies the type of keys, and V specifies the type of values.

74 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Tree Map Class – Example #1

/*This example demonstrate the TreeMap Class*/


import java.util.*;

public class TreeMapDemo {


public static void main(String args[]){
TreeMap<String, Double> tm = new TreeMap<String, Double>();
System.out.println("Size of the TreeMap is "+tm.size());
tm.put("John Doe", 4343.43);
tm.put("Tom Smith",145.23);
tm.put("Jane Baker", 1450.78);
tm.put("Ralph Smith",-18.76);
System.out.println("Elements in the TreeMap "+tm);
System.out.println("Size of the TreeMap is "+tm.size());
Set<Map.Entry<String, Double>> set = tm.entrySet();

75 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Hash Map Class– Example #1

for(Map.Entry<String, Double> me:set) {


System.out.print(me.getKey()+":");
Output:
System.out.println(me.getValue());
Size of the LinkedHashMap is 0
}
Elements in the LinkedHashMap {John
}
Doe=4343.43, Tom Smith=145.23, Jane
}
Baker=1450.78, Ralph Smith=-18.76}
Size of the LinkedHashMap is 4
John Doe:4343.43
Tom Smith:145.23
Jane Baker:1450.78
Ralph Smith:-18.76

76 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

Accessing Collections using Iterator

• Iterator is an object that implements either the Iterator or the ListIterator interface.

• Iterator enables you to cycle through a collection, obtaining or removing elements.

• ListIterator extends Iterator to allow bidirectional traversal of a list, and the modification of elements.

• Iterator and ListIterator are generic interfaces which are declared as shown here:

interface Iterator <E>

interface ListIterator <E>

Here, E specifies the type of objects being iterated.

77 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Iterator Interface

• The methods declared by Iterator are summarized

78 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The List Iterator Interface

• The methods declared by List Iterator are summarized

79 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

Accessing Collections using Iterator – Example #1

/*This example demonstrate the Collections using Iterator*/


import java.util.*;

public class IteratorDemo01 {


public static void main(String args[]) {
ArrayList <String> Arr = new ArrayList<String>(); //Create an Arraylist
System.out.println("Initial Size of Array List is "+Arr.size());
Arr.add("C");
Arr.add("A");
Arr.add("E");
Arr.add("B");
Arr.add("D");
Arr.add("F");
Arr.add(1, "G");
System.out.println("After Insert the Size of Array List is "+Arr.size());

80 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

Accessing Collections using Iterator – Example #1

System.out.println("Contents of ArrayList using Iterator");


Iterator<String> itr = Arr.iterator(); //Iterator
while(itr.hasNext()) {
String element = itr.next();
System.out.print(element+" ");
}
System.out.println();
ListIterator<String> litr = Arr.listIterator(); //ListIterator
while(litr.hasNext()) {
String element = litr.next();
litr.set(element+"+");
}
System.out.println("Modified Contents of ArrayList using Iterator");
itr = Arr.iterator(); //Iterator

81 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

Accessing Collections using Iterator – Example #1

while(itr.hasNext()) {
String element = itr.next();
System.out.print(element+" ");
}
System.out.println();
System.out.println("Modified Contents of ArrayList in Backward using ListIterator");
while(litr.hasPrevious()) {
String element = litr.previous();
System.out.print(element+" ");
}
}
}

82 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

Accessing Collections using Iterator – Output

Output:
Initial Size of Array List is 0
After Insert the Size of Array List is 7
Contents of ArrayList using Iterator
CGAEBDF
Modified Contents of ArrayList using Iterator
C+ G+ A+ E+ B+ D+ F+
Modified Contents of ArrayList in Backward using ListIterator
F+ D+ B+ E+ A+ G+ C+

83 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

Spliterators

• JDK 8 added another type of iterator called a spliterator that is defined by the Spliterator interface.

• A spliterator cycles through a sequence of elements and it is similar to the iterators. However, the

techniques required to use it differ.

• It offers substantially more functionality than does either Iterator or ListIterator.

• It provide support for parallel iteration of portions of the sequence. Thus, Spliterator supports parallel

programming.

• It offers a streamlined approach that combines the hasNext and next operations into one method.

84 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Spliterator Interface

• Spliterator is a generic interface that is declared like this:

interface Spliterator<T>

• Here, T is the type of elements being iterated.

• The methods declared by Spliterator are summarized


Method Description
int characteristics() Returns a set of characteristics of this Spliterator and
its elements.
long estimateSize() Returns an estimate of the number of elements that
would be encountered by
a forEachRemaining(java.util.function.Consumer<?
super T>) traversal, or returns Long.MAX_VALUE if
infinite, unknown, or too expensive to compute.
default void forEachRemaining (Consumer<? Performs the given action for each remaining
super T> action) element, sequentially in the current thread, until all
elements have been processed or the action throws an
exception.
85 Collections in Java | © SmartCliff | Internal | Version 1.0
Collections in Java

The Spliterator Interface

• The methods declared by Spliterator are summarized

Method Description
default Comparator<? super T> If this Spliterator's source is SORTED by a Comparator, returns
getComparator() that Comparator.
default long Convenience method that returns estimateSize() if this Spliterator
getExactSizeIfKnown() is SIZED, else -1.
default boolean Returns true if this Spliterator's characteristics() contain all of the
hasCharacteristics given characteristics.
(int characteristics)
boolean tryAdvance If a remaining element exists, performs the given action on it,
(Consumer<? super T> action) returning true; else returns false.
Spliterator<T> trySplit() If this spliterator can be partitioned, returns a Spliterator covering
elements, that will, upon return from this method, not be covered by
this Spliterator.

86 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Spliterator Class – Example #1

/*This example demonstrate the Spliterator*/


import java.util.*;

public class SpliteratorDemo01 {


public static void main(String args[]) {
//Create an Arraylist
ArrayList <Double> Arr = new ArrayList<Double>();
System.out.println("Initial Size of Array List is "+Arr.size());
Arr.add(1.0);
Arr.add(2.0);
Arr.add(3.0);
Arr.add(4.0);
Arr.add(5.0);
Arr.add(6.0);

87 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Spliterator Class – Example #1

//Use tryAdvance to print elements


System.out.println("Contents of ArrayList using tryAdvance ");
Spliterator<Double> sitr = Arr.spliterator();
while(sitr.tryAdvance((n)->System.out.print(n+" ")));
System.out.println();
//Use forEachRemaining to print elements
System.out.println("Contents of ArrayList using forEachRemaining ");
sitr = Arr.spliterator();
sitr.forEachRemaining((n)->System.out.print(n+" "));
System.out.println();
System.out.println("Size of Array List after insertion is "+Arr.size());
}
}
88 Collections in Java | © SmartCliff | Internal | Version 1.0
Collections in Java

The Spliterator Class – Output

Output:
Initial Size of Array List is 0
Contents of ArrayList using tryAdvance
1.0 2.0 3.0 4.0 5.0 6.0
Contents of ArrayList using forEachRemaining
1.0 2.0 3.0 4.0 5.0 6.0
Size of Array List after insertion is 6

89 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

Storing User defined Classes in Collections – Example #1

/*This example demonstrate the Collections with User defined class*/


import java.util.*;
class Address{
private String name;
private String street;
private String city;
private String state;
private String code;
Address(String n, String s,String c,String st,String cd){
name = n;
street = s;
city = c;
state = st;
code = cd;
}

90 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

Storing User defined Classes in Collections – Example #1

public String toString() {


return name +" "+street+" "+city+" "+state+" "+code;
}}
public class UserDefinedCollectionsDemo01 {
public static void main(String args[]) {
LinkedList<Address> lst = new LinkedList<Address>();
//Add element to the linked list
lst.add(new Address("John Doe","11 Oak Ave","Urbana","IL","61801"));
lst.add(new Address("Ralph Baker","1142 Maple Lane","Mahomet","IL","61853"));
lst.add(new Address("Tom Carlton","867 Elm st","Champaign","IL","61820"));
//Display the Details
for(Address element:lst) {
System.out.println(element);
}
}}

91 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

Storing User defined Classes in Collections– Output

Output:
John Doe 11 Oak Ave Urbana IL 61801
Ralph Baker 1142 Maple Lane Mahomet IL 61853
Tom Carlton 867 Elm st Champaign IL 61820

92 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

Quiz

1. What is Collection in Java?

a) A group of Classes b) A group of Objects

c) A group of Interfaces d) None of the above

b) A group of Objects

93 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

Quiz

2. Which of the following is not in the Collections in Java ?

a) Array b) Vector

c) Stack d) HashSet

a) Array

94 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

Quiz

3. Which of the following is the interface?

a) ArrayList b) HashSet

c) Queue d) TreeMap

c) Queue

95 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

Quiz

4. The Dictionary class provides the capability to store

a) key b) key-value pair

c) value d) None of these

b) key-value pair

96 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

Quiz

5. Which of the following classes are used to avoid duplicates?

a) ArrayList b) HashSet

c) LinkedList d) LinkedHashSet

b) HashSet & d) LinkedHashSet

97 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

Quiz

6. In which of the following package, are all of the collection

classes present?

a) java.net b) java.lang

c) java.awt d) java.util

d) java.util

98 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

Quiz

7. Which of the following interface is not a part of Java’s

collection framework ?

a) SortedList b) Set

c) List d) SortedMap

a) SortedList

99 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

Quiz

8. Which of these interface handle sequences?

a) Set b) Comparator

c) Collection d) List

d) List

100 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

Quiz

9. Which of these methods deletes all the elements from

invoking collection ?

a) clear () b) reset ()

c) delete () d) refresh ()

a) clear ()

101 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

Quiz
10. What is the output of the following code
import java.util.*;
public class Test {
public static void main(String args[]) {
ArrayList <Integer> al = new ArrayList<Integer>();
for (int i = 5; i > 0; i--)
al.add(i);
for(Integer ele:al) {
System.out.print(ele+" ");
}
}
}

a) 12345 b) 54321

c) 13579 d) 02468

102 Collections in Java | © SmartCliff | Internal | Version 1.0 b) 54321


THANK YOU

You might also like