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

Java Collections

The document discusses various collection classes in Java like List, Map, Set, Queue. It provides examples of how to use common List classes like ArrayList, LinkedList, Vector. It also covers Map classes like HashMap, TreeMap and their usage. Other collection classes discussed are Set, Queue, PriorityQueue with examples of adding/removing elements.

Uploaded by

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

Java Collections

The document discusses various collection classes in Java like List, Map, Set, Queue. It provides examples of how to use common List classes like ArrayList, LinkedList, Vector. It also covers Map classes like HashMap, TreeMap and their usage. Other collection classes discussed are Set, Queue, PriorityQueue with examples of adding/removing elements.

Uploaded by

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

@techwithvishalraj

Java
Collections
Hierarchy of Collection Framework @techwithvishalraj
@techwithvishalraj

Collections in Java

The Collection in Java is a framework that provides an architecture to


store and manipulate the group of objects.

Java Collections can achieve all the operations that you perform on a
data such as searching, sorting, insertion, manipulation and deletion.

Java Collection means a single unit of objects.

The java.util package contains all the classes and interfaces for the
Collection framework except Iterable interface which is present in
java.lang package.
List Interface
@techwithvishalraj

In List store the ordered collection of objects.


It can have duplicate values.
List interface is implemented by the classes ArrayList, LinkedList, Vector,
and Stack.

List <data-type> list1= new ArrayList();


List <data-type> list2 = new LinkedList();
List <data-type> list3 = new Vector();
List <data-type> list4 = new Stack();

Map Interface

A map contains key and value pair. Each key and value pair is known as an
entry. A Map contains unique keys.
A Map is useful if you have to search, update or delete elements on the basis
of a key.
A Map doesn't allow duplicate keys, but you can have duplicate values.
HashMap and LinkedHashMap allow null keys and values, but TreeMap
doesn't allow any null key or value.

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


Map<Integer,String> map = new TreeMap<Integer, String>();
Set Interface @techwithvishalraj

A Set does not allow duplicate elements.


Sets typically do not guarantee any specific order for their elements.

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


Set<String> set = new LinkedHashSet<>();
Set<Integer> set= new TreeSet<>();

Queue Interface

A queue is a linear data structure that follows the "first-in, first-out" (FIFO)
principle.
It is an ordered list of objects.

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


Queue<String> list = new LinkedList<>();
Queue<String> deque = new ArrayDeque<>();
ArrayList Class
@techwithvishalraj

ArrayList can grow or shrink dynamically as elements are added or removed.


You can access elements in an ArrayList using an index. The index starts at 0
for the first element and goes up to size() - 1 for the last element.
ArrayList can contain duplicate elements.
Elements in an ArrayList maintain the order in which they were added.

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

list.add(1);
list.add(5);

System.out.println(list); ----> [1, 5]

list.size() ----> 2
list.isEmpty() ----> false
list.remove(1) ----> 1 is the index
list.toString() ----> [1, 5]

list.contains(1) -----> true


Object[] arr=list.toArray(); ----> [1, 5]
list.add(1, 9); ----> [1, 9, 5]
list.clear();

list.addAll(list1);
LinkedList Class
@techwithvishalraj

LinkedList is a class that implements the List interface and is used to create
and manipulate doubly-linked lists.
A doubly-linked list is a data structure in which each element is a node that
contains a reference to both the next and previous nodes in the list.

LinkedList<String> linkedList = new LinkedList<>();

linkedList.add("First");
linkedList.addLast("Last");
linkedList.addFirst("NewFirst");

String firstElement = linkedList.getFirst();


String lastElement = linkedList.getLast();
String secondElement = linkedList.get(1);

linkedList.remove("First");
linkedList.removeFirst();
linkedList.removeLast();

boolean containsElement = linkedList.contains("First");


int size = linkedList.size();
boolean isEmpty = linkedList.isEmpty();
linkedList.clear();
Stack Class @techwithvishalraj

Stack class follows the "last-in, first-out" (LIFO) principle.


If the stack is empty, it throws an EmptyStackException.

Stack<Integer> stack = new Stack<>();

stack.push(10);
stack.push(20);
stack.push(30);

int topElement = stack.peek();

int poppedElement = stack.pop();

boolean isEmpty = stack.empty();

int position = stack.search(20); ----> return position from the top of


the stack and if not found return -1.
Vector Class @techwithvishalraj

Vector is a legacy data structure in Java that is similar to an ArrayList.


It is part of the Java Collections Framework and provides dynamic array-like
functionality.
However, Vector is synchronized by default, which means it is thread-safe but
may be less efficient than ArrayList in single-threaded scenarios.

Vector<Integer> numbers = new Vector<>();

numbers.add(10);
numbers.add(20);
numbers.add(30);
numbers.add(1, 25);

int size = numbers.size();


int firstNumber = numbers.get(0);

numbers.remove(2);
numbers.clear();

boolean containsElement = numbers.contains(10);


boolean isEmpty = numbers.isEmpty();
PriorityQueue Class @techwithvishalraj

Elements with higher priority are dequeued before elements with lower priority.
The priority queue processes elements in ascending order by default.

PriorityQueue<Integer> priorityQueue = new PriorityQueue<>();

priorityQueue.add(5);
priorityQueue.add(2);
priorityQueue.add(8);
priorityQueue.add(1);

// Retrieving and removing the highest priority element


int highestPriority = priorityQueue.poll(); ----> 1

int peekedElement = priorityQueue.peek(); ----> 2

// Checking if an element exists and removing it


boolean removed = priorityQueue.remove(8); ----> true/false

int size = priorityQueue.size(); ----> 2


boolean isEmpty = priorityQueue.isEmpty(); ----> true/false

// Iterating through the PriorityQueue(ascending order by default)


while (!priorityQueue.isEmpty()) {
System.out.println(priorityQueue.poll()); ----> 2 4 5
}
ArrayDeque Class @techwithvishalraj

ArrayDeque is a double-ended queue implementation in Java that provides


methods for adding and removing elements from both ends efficiently.

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

deque.addFirst(1);
deque.addLast(2);
deque.offerFirst(4);
deque.offerLast(3);

int frontElement = deque.getFirst();


int rearElement = deque.getLast();

int removedFront = deque.removeFirst();


int removedRear = deque.removeLast();

int size = deque.size();


boolean isEmpty = deque.isEmpty();
deque.clear();

Note:
addFirst() may throw an exception if the deque is full.
offerFirst() returns false if the element cannot be added due to
capacity constraints but does not throw an exception.
HashSet Class
@techwithvishalraj

HashSet is an implementation of the Set interface that provides a collection


of unique elements.
It is used to store a group of distinct values without any specific order.

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

set.add("Apple");
set.add("Banana");
set.add("Cherry");

for (String fruit : set) {


System.out.println(fruit); ----> Apple Cherry Banana
}

set.remove("Banana");

boolean containsCherry = set.contains("Cherry");

int size = set.size();

set.clear();
LinkedHashSet Class @techwithvishalraj

LinkedHashSet combines the features of both a HashSet and a


LinkedHashMap.
It maintains a collection of unique elements like a HashSet, but it also
preserves the order of insertion like a LinkedHashMap. This means that when
you iterate over a LinkedHashSet, the elements are returned in the order in
which they were added.

LinkedHashSet<String> set = new LinkedHashSet<>();

set.add("Apple");
set.add("Banana");
set.add("Cherry");

for (String fruit : set) {


System.out.println(fruit); ----> Apple Banana Cherry
}

int size = set.size();

set.remove("Banana");

boolean containsCherry = set.contains("Cherry");


TreeSet Class
@techwithvishalraj

TreeSet is that it maintains its elements in sorted order.


TreeSet does not allow duplicate elements.
TreeSet uses a Red-Black Tree data structure to maintain its elements in a
sorted manner.
TreeSet provides methods to navigate through the set, such as lower(), floor(),
ceiling(), and higher(), which allow you to find elements that are less than, less
than or equal to, greater than or equal to, or greater than a given element,
respectively.

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

numbers.add(5);
numbers.add(2);
numbers.add(8);
numbers.add(1);
numbers.add(4);

System.out.println(numbers); -----> [1, 2, 4, 5, 8]


System.out.println(numbers.higher(4)); -----> 5
System.out.println(numbers.lower(4)); -----> 2

boolean containsFive = numbers.contains(5); -----> true/false


numbers.isEmpty(); -----> true/false
numbers.remove(2);
int size = numbers.size(); ------> 4
TreeMap Class
@techwithvishalraj

TreeMap implements the Map interface and is based on a Red-Black Tree.


Maintains the key-value pairs in sorted order based on the keys.
Each key in a TreeMap must be unique, but values can be duplicated.
Attempting to add a duplicate key will replace the existing value associated with
that key.
A HashMap allows null values but not null key.

TreeMap<Integer, String> treeMap = new TreeMap<>();

treeMap.put(3, "Three");
treeMap.put(1, "One");
treeMap.put(2, "Two");

String value = treeMap.get(2); -------> Two

for (Integer key : treeMap.keySet()) {


System.out.print(key + ": " + treeMap.get(key)); 1: One 2: Two 3: Three
}

boolean containsKey = treeMap.containsKey(4); -------> true/false

treeMap.remove(1);
int size = treeMap.size(); -------> 2
treeMap.isEmpty();
treeMap.clear();
HashMap Class
@techwithvishalraj

HashMap is store and manage data in key-value pairs.


A HashMap is based on the principle of a hash table, which allows for fast
retrieval and insertion of data.
keys must be unique within a HashMap, values can be duplicated.
HashMap does not guarantee any specific order.
A HashMap allows null values and a single null key.

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

scores.put("Alice", 95);
scores.put("Bob", 88);
scores.put("Charlie", 92);

int aliceScore = scores.get("Alice"); ------> 95

boolean hasKey = scores.containsKey("Bob"); ------> true/false

for (String key : scores.keySet()) {


System.out.print(key+": "+scores.get(key)); ---> Bob: 88 Alice: 95 Charlie: 92
}

scores.remove("Charlie");

int size = scores.size(); ------> 2


scores.isEmpty() ------> true/false
scores.clear();
LinkedHashMap Class
@techwithvishalraj

In LinkedHashMap, the elements are returned in the order in which they were
added to the map or in the order in which they were most recently accessed,
depending on the constructor used.
keys must be unique, values can be duplicated.
It allows null keys and values.

// true parameter in below constructor means access-order enable


LinkedHashMap<String, Integer> map = new LinkedHashMap<>(16, 0.75f, true);
map.put("One", 1);
map.put("Two", 2);
map.put("Three", 3);
// Access an element (this moves it to the end of the access-order)
map.get("One");
// Iterate through the elements (in access-order)
for (Map.Entry<String, Integer> entry : map.entrySet()) {
Sop(entry.getKey() +":"+ entry.getValue()); -----> Two: 2 Three: 3 One: 1
}

// no parameter constructor means insertion-order


LinkedHashMap<String, Integer> map = new LinkedHashMap<>();
map.put("One", 1);
map.put("Two", 2);
map.put("Three", 3);
map.get("One");
for (String key : map.keySet()) {
System.out.println(key + ": " + map.get(key)); -----> One: 1 Two: 2 Three: 3
}
Iterator Interface
@techwithvishalraj

Present in the java.util package.


iterator is an object that allows you to traverse and manipulate elements in a
collection (such as lists, sets, or maps) in a consistent and standardized way.

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


fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
Iterator<String> iterator = fruits.iterator();
while (iterator.hasNext()) {
String fruit = iterator.next();
iterator.remove();
System.out.println(fruit);
}
Map<String, Integer> map = new HashMap<>();
map.put("Alice", 25);
map.put("Bob", 30);
map.put("Charlie", 22);
Iterator<Map.Entry<String, Integer>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Integer> entry = iterator.next();
String key = entry.getKey();
Integer value = entry.getValue();
System.out.println("Key: " + key + ", Value: " + value);
}
Collections Class
@techwithvishalraj

Present in the java.util package.


Collections class uses only static methods for computations.

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

list.add(1);
list.add(6);
list.add(0);

Collections.addAll(list, 8, 3);
Integer[] arr = {5, 4, 1};
Collections.addAll(list, arr);

System.out.println(list);
int max=Collections.max(list);
int min=Collections.min(list);
int frequency=Collections.frequency(list, 1);
int index = Collections.binarySearch(list, 4);
System.out.println(max+" "+ min +" "+ frequency+" "+ index);
Collections.reverse(list);
System.out.println(list);
Thank
you!

EXPLORE MORE

@techwithvishalraj

You might also like