5.collections in Java
5.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
Collections - Introduction
• 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
Collections Interface
Collections Interfaces
• In addition to the collection interfaces, collections also use the Comparator, RandomAccess,
• By implementing RandomAccess, a list indicates that it supports efficient, random access to its
elements.
Collections Interfaces
• To provide the greatest flexibility in their use, the collection interfaces allow some methods to be
optional.
• Collections that do not allow their contents to be changed are called unmodifiable.
UnsupportedOperationException is thrown.
• The Collection interface is the foundation upon which the Collections Framework is built because it
interface Collection<E>
Here, E specifies the type of objects that the collection will hold.
• Collection declares the core methods that all collections will have. These methods are
• 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.
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
• In addition to the methods defined by Collection, List defines some of its own
• The ArrayList class extends AbstractList and implements the List interface.
class ArrayList<E>
Here, E specifies the type of objects that the list will hold.
• 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.
• The LinkedList class extends AbstractSequentialList and implements the List, Deque, and Queue
interfaces.
class LinkedList<E>
Here, E specifies the type of objects that the list will hold.
• LinkedList(Collection<? extends E> c) – builds a linked list that is initialized with the elements of
the collection c
• It is similar to ArrayList.
• It is synchronized and contains many methods that are not the part of Collection framework.
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
• The stack contains all of the methods of Vector class and also provides its methods like boolean
• 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.
interface Set<E>
Here, E specifies the type of objects that the set will hold.
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
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
• The LinkedHashSet class extends HashSet and adds no members of its own.
class LinkedHashSet<E>
Here, E specifies the type of objects that the set will hold.
• LinkedHashSet maintains a linked list of the entries in the set, in the order in which they were
inserted.
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
• The SortedSet interface extends Set and declares the behavior of a set sorted in ascending order.
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
• In addition to the methods defined by Collection, Sorted Set defines some of its own
• collection that supports the retrieval of elements based on the closest match to
interface NavigableSet<E>
Here, E specifies the type of objects that the set will hold. In addition to the
• 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.
class TreeSet<E>
Here, E specifies the type of objects that the set will hold.
• The Queue interface extends Collection and declares the behavior of a queue, which is often a first-
• There are types of queues in which the ordering is based upon other criteria. Queue is a generic
interface Queue<E>
Here, E specifies the type of objects that the queue will hold.
class PriorityQueue<E>
• 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.
interface Deque<E>
Here, E specifies the type of objects that the deque will hold.
• In addition to the methods that it inherits from Queue, Deque adds those methods summarized
• The ArrayDeque class extends AbstractCollection and implements the Deque interface.
class ArrayDeque<E>
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
• A key is an object that you use to retrieve a value at a later date. Given a key and a value, you can
• After the value is stored, you can retrieve it by using its key.
Here, K specifies the type of keys, and V specifies the type of values.
• The HashMap class extends AbstractMap and implements the Map interface.
• This allows the execution time of get( ) and put( ) to remain constant even for large sets.
Here, K specifies the type of keys, and V specifies the type of values
• 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.
Here, K specifies the type of keys, and V specifies the type of values.
• It ensures that the entries are maintained in ascending order based on the keys.
Here, K specifies the type of keys, and V specifies the type of values.
• The TreeMap class extends AbstractMap and implements the NavigableMap interface.
• 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.
Here, K specifies the type of keys, and V specifies the type of values.
• Iterator is an object that implements either the Iterator or the ListIterator interface.
• 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:
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+" ");
}
}
}
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+
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
• 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.
interface Spliterator<T>
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.
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
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
Quiz
b) A group of Objects
Quiz
a) Array b) Vector
c) Stack d) HashSet
a) Array
Quiz
a) ArrayList b) HashSet
c) Queue d) TreeMap
c) Queue
Quiz
b) key-value pair
Quiz
a) ArrayList b) HashSet
c) LinkedList d) LinkedHashSet
Quiz
classes present?
a) java.net b) java.lang
c) java.awt d) java.util
d) java.util
Quiz
collection framework ?
a) SortedList b) Set
c) List d) SortedMap
a) SortedList
Quiz
a) Set b) Comparator
c) Collection d) List
d) List
Quiz
invoking collection ?
a) clear () b) reset ()
c) delete () d) refresh ()
a) clear ()
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