Java Unit-4
Java Unit-4
list_1.addAll(list_2);
System.out.println("Elements of list_1: " + list_1);
list_1.remove(0);
System.out.println(list_1);
list_1.retainAll(list_2);
System.out.println(list_1);
list_1.removeAll(list_2);
System.out.println(list_1);
list_2.clear();
System.out.println(list_2);
}
}
The java LIST interface:
• The List interface is a child interface of the Collection interface. The
List interface is available inside the java.util package. It defines the
methods that are commonly used by classes like ArrayList, LinkedList,
Vector, and Stack.
• The List interface extends Collection interface.
• The List interface allows duplicate elements.
• The List interface preserves the order of insertion.
• The List allows to access the elements based on the index value that
starts with zero.
import java.util.ArrayList;
import java.util.List;
public class ListInterfaceExample {
public static void main(String[] args) {
List list_1 = new ArrayList();
List<String> list_2 = new ArrayList<String>();
list_1.add(0, 10);
list_1.add(1, 20);
list_2.add(0, “csd");
list_2.add(1, “csc");
list_2.add(2, “cse");
list_1.addAll(1, list_2);
System.out.println("\nElements of list_1: " + list_1);
System.out.println("\nElement at index 3: " + list_1.get(3));
System.out.println("\nSublist : " + list_1.subList(2, 5));
list_1.set(2, 10);
System.out.println("\nAfter updating the value at index 2: " + list_1);
System.out.println("\nIndex of value 10: " + list_1.indexOf(10));
System.out.println("\nLast index of value 10: " + list_1.lastIndexOf(10));
}}
Java Queue Interface:
• The Queue interface is a child interface of the Collection interface.
The Queue interface is available inside the java.util package.
• It defines the methods that are commonly used by classes like
PriorityQueue and ArrayDeque.
• The Queue is used to organize a sequence of elements prior to the
actual operation.
• The Queue interface extends Collection interface.
• The Queue interface allows duplicate elements.
• The Queue interface preserves the order of insertion.
im p o rt ja va .u til.*;
queue.re m o ve ();
Sys te m .out.p rintln ("\ n Ele m e n ts a fte r He a d re m o va l - " + queue);
queue.p o ll();
Sys te m .out.p rintln ("\ n Ele m e n ts a fte r o n e m o re He a d re m o va l - "
+ queue);
}
• The Deque interface:
is a child interface of the Queue interface. The Deque interface is
available inside the java.util package. It defines the methods that are
used by class ArrayDeque.
• The Deque interface extends Queue interface.
• The Deque interface allows duplicate elements.
• The Deque interface preserves the order of insertion.
import java.util.*;
public class DequeInterfaceExample {
public static void main(String[] args) {
Deque deque = new ArrayDeque();
deque.addFirst(10);
deque.addLast(20);
deque.offerFirst(5);
deque.offerLast(25);
deque.push(2);
System.out.println("\nElements of deque - " + deque);
System.out.println("\nFirst element - " + deque.getFirst());
System.out.println("\nLast element - " + deque.getLast());
System.out.println("\nFirst element - " + deque.peekFirst());
System.out.println("\nLast element - " + deque.peekLast());
System.out.println("\nRemove first element - " + deque.pop());
System.out.println("\nRemove one more first element - " + deque.pollFirst());
System.out.println("\nRemove last element - " + deque.pollLast());
System.out.println("\nRemove one more first element - " + deque.removeFirst());
System.out.println("\nRemove one more last element - " + deque.removeLast());
}
Java SortedSet Interface
1. Set Interface
• The Set interface is a child interface of Collection interface. It does not defines
any additional methods of it, it has all the methods that are inherited from
Collection interface.
• The Set interface does not allow duplicates. Set is a generic interface.
2. SortedSet Interface
• The SortedSet interface is a child interface of the Set interface. The SortedSet
interface is available inside the java.util package.
• It defines the methods that are used by classes HashSet, LinkedHashSet, and
TreeSet.
• The SortedSet interface extends Set interface.
• The SortedSet interface does not allow duplicate elements.
• The SortedSet interface organize the elements based on the ascending order.
• The SortedSet interface defines the following methods.
import java.util.*;
public class SortedSetInterfaceExample {
public static void main(String[] args) {
SortedSet sortedSet = new TreeSet();
sortedSet.add(10);
sortedSet.add(20);
sortedSet.add(5);
sortedSet.add(40);
sortedSet.add(30);
System.out.println("\nElements of sortedSet: " + sortedSet);
System.out.println("\nFirst element: " + sortedSet.first());
System.out.println("\nLast element: " + sortedSet.last());
System.out.println("\nSubset with upper limit: " + sortedSet.headSet(30));
System.out.println("\nSubset with lower limit: " + sortedSet.tailSet(30));
System.out.println("\nSubset with upper and lower limit: " + sortedSet.subSet(10, 30));
}
Java NavigableSet Interface:
The NavigableSet interface is a child interface of the SortedSet
interface. The NavigableSet interface is available inside the java.util
package. It defines the methods that are used by class TreeSet.
1. The NavigableSet interface extends SortedSet interface.
2. The SortedSet interface does not allow duplicate elements.
3. The SortedSet interface organize the elements based on the
ascending order.
The NavigableSet interface defines several utility methods that are used
in the TreeSet class and they are as follows.
Example
import java.util.*;
public class NavigableSetInterfaceExample {
public static void main(String[] args) {
NavigableSet navSet = new TreeSet();
navSet.add(10);
navSet.add(20);
navSet.add(5);
navSet.add(40);
navSet.add(30);
System.out.println("\nElements of sortedSet: " + navSet);
System.out.println("\nSmallest element from subSet of larger than 25: " + navSet.ceiling(25));
System.out.println("\nLargest element from subSet of smaller than 25: " + navSet.floor(25));
System.out.println("\nSmallest element from subSet of larger than 25: " + navSet.higher(25));
System.out.println("\nLargest element from subSet of smaller than 25: " + navSet.lower(25));
System.out.println("\nSubset with upperBound, including it: " + navSet.headSet(30, true));
System.out.println("\nSubset with upperBound, excluding it: " + navSet.headSet(30, false));
System.out.println("\nSubset with lowwerBound, including it: " + navSet.tailSet(30, true));
System.out.println("\nSubset with lowerBound, excluding it: " + navSet.tailSet(30, false));
System.out.println("\nRemove the first element: " + navSet.pollFirst());
System.out.println("\nRemove the last element: " + navSet.pollLast());
}
• Java ArrayList Class
• The ArrayList class is a part of java collection framework. It is available inside
the java.util package. The ArrayList class extends AbstractList class and
implements List interface.
• The elements of ArrayList are organized as an array internally. The default size
of an ArrayList is 10.
• The ArrayList class is used to create a dynamic array that can grow or shrunk
as needed.
1. The ArrayList is a child class of AbstractList
2. The ArrayList implements interfaces like List, Serializable, Cloneable, and
RandomAccess.
3. The ArrayList allows to store duplicate data values.
4. The ArrayList allows to access elements randomly using index-based
accessing.
5. The ArrayList maintains the order of insertion.
ArrayList class declaration
• The ArrayList class has the following declaration.
Example
public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable,
Serializable
• ArrayList class constructors
• The ArrayList class has the following constructors.
• ArrayList( ) - Creates an empty ArrayList.
• ArrayList(Collection c) - Creates an ArrayList with given collection of elements.
• ArrayList(int size) - Creates an empty ArrayList with given size (capacity).
Operations on ArrayList
The ArrayList class allow us to perform several operations like adding, accesing, deleting,
updating, looping, etc. Let's look at each operation with examples.
• Adding Items
• The ArrayList class has the following methods to add items.
• boolean add(E element) - Appends given element to the ArrayList.
• boolean addAll(Collection c) - Appends given collection of elements to the ArrayList.
• void add(int index, E element) - Inserts the given element at specified index.
• boolean addAll(int index, Collection c) - Inserts the given collection of elements at specified
index.
an example program to illustrate adding items to the ArrayList.
Example:
import java.util.*;
public class ArrayListExample {
public static void main(String[] args) {
ArrayList<String> list_1 = new ArrayList<String>();
ArrayList list_2 = new ArrayList();
//Appending
list_1.add(“CMR");
System.out.println("list_1: " + list_1);
list_1.add(“CAMPUS");
System.out.println("list_1: " + list_1);
//Inserting at specified index
list_1.add(1, “TECHNICAL");
System.out.println("list_1: " + list_1);
//Appending a collection of elements
list_2.addAll(list_1);
System.out.println("list_2: " + list_2);
//Inserting collection of elements at specified index
list_2.addAll(2, list_1);
System.out.println("list_2: " + list_2);
}
Accessing Items
• The ArrayList class has the following methods to access items.
• E get(int index) - Returns element at specified index from the
ArrayList.
• ArrayList subList(int startIndex, int lastIndex) - Returns an ArrayList
that contails elements from specified startIndex to lastIndex-1 from
the invoking ArrayList.
• int indexOf(E element) - Returns the index value of given element first
occurence in the ArrayList.
• int lastIndexOf(E element) - Returns the index value of given element
last occurence in the ArrayList.
import java.util.*;
public class ArrayListExample {
list_1.add(“CMR");
list_1.add(“TECHNICAL ");
list_1.add("CAMPUS");
list_1.add("-");
list_1.add("Java");
list_1.add("Tutorial");
list_1.add("Class");
}
}
• Updating Items
• The ArrayList class has the following methods to update or change
items.
• E set(int index, E newElement) - Replace the element at specified
index with newElement in the invoking ArrayList.
• ArrayList replaceAll(UnaryOperator e) - Replaces each element of
invoking ArrayList with the result of applying the operator to that
element.
Example
import java.util.*;
public class ArrayListExample {
public static void main(String[] args) {
ArrayList<String> list_1 = new ArrayList<String>();
list_1.add(“CMR");
list_1.add(“TECHNICAL");
list_1.add("CAMPUS");
list_1.add("-");
list_1.add("Java");
list_1.add("Tutorial");
list_1.add("Class");
System.out.println("\nList before update: " + list_1);
list_1.set(3, ":");
System.out.println("\nList after update: " + list_1);
list_1.replaceAll(e -> e.toUpperCase());
System.out.println("\nList after update: " + list_1);
}
}
• Removing Items
The ArrayList class has the following methods to remove items.
• E remove(int index) - Removes the element at specified index in
the invoking ArrayList.
• boolean remove(Object element) - Removes the first occurence
of the given element from the invoking ArrayList.
• boolean removeAll(Collection c) - Removes the given collection
of elements from the invoking ArrayList.
• void retainAll(Collection c) - Removes all the elements except the
given collection of elements from the invoking ArrayList.
• boolean removeIf(Predicate filter) - Removes all the elements
from the ArrayList that satisfies the given predicate.
• void clear( ) - Removes all the elements from the ArrayList.
Java LinkedList Class
• The LinkedList class is a part of java collection framework. It is available
inside the java.util package. The LinkedList class extends
AbstractSequentialList class and implements List and Deque interface.
• The elements of LinkedList are organized as the elements of linked list
data structure.
• The LinkedList class is used to create a dynamic list of elements that can
grow or shrunk as needed.
• The LinkedList is a child class of AbstractSequentialList
• The LinkedList implements interfaces like List, Deque, Cloneable, and
Serializable.
• The LinkedList allows to store duplicate data values.
• The LinkedList maintains the order of insertion.
LinkedList class constructors
The LinkedList class has the following constructors.
• LinkedList( ) - Creates an empty List.
• LinkedList(Collection c) - Creates a List with given collection of elements.
Operations on LinkedList
The LinkedList class allow us to perform several operations like adding, accesing, deleting, updating, looping, etc.
Let's look at each operation with examples.
Adding Items
The LinkedList class has the following methods to add items.
• boolean add(E element) - Appends given element to the List.
• boolean addAll(Collection c) - Appends given collection of elements to the List.
• void add(int position, E element) - Inserts the given element at specified position.
• boolean addAll(int position, Collection c) - Inserts the given collection of elements at specified position.
• void addFirst(E element) - Inserts the given element at beggining of the list.
• void addLast(E element) - Inserts the given element at end of the list.
• boolean offer(E element) - Inserts the given element at end of the list.
• boolean offerFirst(E element) - Inserts the given element at beggining of the list.
• boolean offerLast(E element) - Inserts the given element at end of the list.
• void push(E element) - Inserts the given element at beggining of the list.
im p o rt ja va .u t il.*;
Lin ke d Lis t <St rin g > list_1 = n e w Lin ke d Lis t <St rin g >();
Lin ke d Lis t list_2 = n e w Lin ke d Lis t ();
list_2.a d d (10 );
list_2.a d d (20 );
list_2.a d d Firs t (5);
list_2.a d d La s t (25);
list_2.o ffe r(2);
list_2.o ffe rFirs t (1);
list_2.o ffe rLa s t (10 );
list_2.p u s h (40 );
list_1.a d d All(list_2);
}
Accessing Items
The LinkedList class has the following methods to access items.
• E get(int position) - Returns element at specified position from the LinkedList.
• E element( ) - Returns the first element from the invoking LinkedList.
• E getFirst( ) - Returns the first element from the invoking LinkedList.
• E getLast( ) - Returns the last element from the invoking LinkedList.
• E peek( ) - Returns the first element from the invoking LinkedList.
• E peekFirst( ) - Returns the first element from the invoking LinkedList, and returns null
if list is empty.
• E peekLast( ) - Returns the last element from the invoking LinkedList, and returns null
if list is empty.
• int indexOf(E element) - Returns the index value of given element first occurence in
the LinkedList.
• int lastIndexOf(E element) - Returns the index value of given element last occurence in
the LinkedList.
• E pop( ) - Returns the first element from the invoking LinkedList.
im p o rt ja va .util.*;
}
Java PriorityQueue Class
• The Priority Queue class is a part of java collection framework. It is
available inside the java.util package. The Priority Queue class extends
AbstractQueue class and implements Serializable interface.
• The elements of Priority Queue are organized as the elements of
queue data structure, but it does not follow FIFO principle. The
Priority Queue elements are organized based on the priority heap.
1. The Priority Queue is a child class of AbstractQueue
2. The Priority Queue implements interface Serializable.
3. The Priority Queue allows to store duplicate data values, but not
null values.
4. The Priority Queue maintains the order of insertion.
5. The Priority Queue used priority heap to organize its elements.
PriorityQueue class constructors
• The PriorityQueue class has the following constructors.
• PriorityQueue( ) - Creates an empty PriorityQueue with the default initial
capacity (11) that orders its elements according to their natural ordering.
• PriorityQueue(Collection c) - Creates a PriorityQueue with given
collection of elements.
• PriorityQueue(int initialCapacity) - Creates an empty PriorityQueue with
the specified initial capacity.
• PriorityQueue(int initialCapacity, Comparator comparator) - Creates an
empty PriorityQueue with the specified initial capacity that orders its
elements according to the specified comparator.
• PriorityQueue(PriorityQueue pq) - Creates a PriorityQueue with the
elements in the specified priority queue.
• PriorityQueue(SortedSet ss) - Creates a PriorityQueue with the elements
in the specified SortedSet
Let's consider an example program to illustrate adding items to the PriorityQueue.
Example
import java.util.*;
public class PriorityQueueExample {
public static void main(String[] args) {
PriorityQueue queue = new PriorityQueue();
PriorityQueue anotherQueue = new PriorityQueue();
queue.add(10);
queue.add(20);
queue.add(15);
System.out.println("\nQueue is " + queue);
anotherQueue.addAll(queue);
System.out.println("\nanotherQueue is " + anotherQueue);
anotherQueue.offer(25);
System.out.println("\nanotherQueue is " + anotherQueue);
}
Map Interface in java
• The java collection framework has an interface Map that is available
inside the java.util package. The Map interface is not a subtype of
Collection interface.
• The Map stores the elements as a pair of key and value.
• The Map does not allows duplicate keys, but allows duplicate values.
• In a Map, each key can map to at most one value only.
• In a Map, the order of elements depends on specific
implementations, e.g TreeMap and LinkedHashMap have predictable
order, while HashMap does not.