[go: up one dir, main page]

0% found this document useful (0 votes)
64 views23 pages

COLLECTIONS

Uploaded by

Manasvi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
64 views23 pages

COLLECTIONS

Uploaded by

Manasvi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 23

Hierarchy of Collection Framework

Let us see the hierarchy of Collection framework. The java.util package contains all
the classes and interfaces for the Collection framework.
Set Interface
Set Interface in Java is present in java.util package. It extends the Collection interface. It represents
the unordered set of elements which doesn't allow us to store the duplicate items. We can store at
most one null value in Set. Set is implemented by HashSet, LinkedHashSet, and TreeSet.

Set can be instantiated as:

1. Set<data-type> s1 = new HashSet<data-type>();


2. Set<data-type> s2 = new LinkedHashSet<data-type>();
3. Set<data-type> s3 = new TreeSet<data-type>();

Java HashSet

Java HashSet class is used to create a collection that uses a hash table for storage. It inherits the
AbstractSet class and implements Set interface.

The important points about Java HashSet class are:

o HashSet stores the elements by using a mechanism called hashing.


o HashSet contains unique elements only.
o HashSet allows null value.
o HashSet class is non synchronized.
o HashSet doesn't maintain the insertion order. Here, elements are inserted on the basis of their
hashcode.
o HashSet is the best approach for search operations.
o The initial default capacity of HashSet is 16, and the load factor is 0.75.

Difference between List and Set


A list can contain duplicate elements whereas Set contains unique elements only.

Hierarchy of HashSet class


The HashSet class extends AbstractSet class which implements Set interface. The Set interface
inherits Collection and Iterable interfaces in hierarchical order.
HashSet class declaration
Let's see the declaration for java.util.HashSet class.

1. public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable, Serializ


able

Constructors of Java HashSet class

SN Constructor Description

1) HashSet() It is used to construct a default HashSet.

2) HashSet(int It is used to initialize the capacity of the hash set to the given integer
capacity) value capacity. The capacity grows automatically as elements are
added to the HashSet.
Methods of Java HashSet class

Various methods of Java HashSet class are as follows:

SN Modifier & Type Method Description

1) boolean add(E e) It is used to add the specified element to this set


if it is not already present.

2) void clear() It is used to remove all of the elements from the


set.

4) boolean contains(Object o) It is used to return true if this set contains the


specified element.

5) boolean isEmpty() It is used to return true if this set contains no


elements.

6) Iterator<E> iterator() It is used to return an iterator over the elements


in this set.

7) boolean remove(Object o) It is used to remove the specified element from


this set if it is present.

8) int size() It is used to return the number of elements in the


set.
Java HashSet example ignoring duplicate elements
In this example, we see that HashSet doesn't allow duplicate elements.

1. import java.util.*;
2. class HashSet2{
3. public static void main(String args[]){
4. //Creating HashSet and adding elements
5. HashSet<String> set=new HashSet<String>();
6. set.add("Ravi");
7. set.add("Vijay");
8. set.add("Ravi");
9. set.add("Ajay");
10. //Traversing elements
11. Iterator<String> itr=set.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }
Ajay
Vijay
Ravi

Java HashSet example to remove elements


Here, we see different ways to remove an element.

1. import java.util.*;
2. class HashSet3{
3. public static void main(String args[]){
4. HashSet<String> set=new HashSet<String>();
5. set.add("Ravi");
6. set.add("Vijay");
7. set.add("Arun");
8. set.add("Sumit");
9. System.out.println("An initial list of elements: "+set);
10. //Removing specific element from HashSet
11. set.remove("Ravi");
12. System.out.println("After invoking remove(object) method: "+set);
13. HashSet<String> set1=new HashSet<String>();
14. set1.add("Ajay");
15. set1.add("Gaurav");
16. set.addAll(set1);
17. System.out.println("Updated List: "+set);
18. //Removing all the new elements from HashSet
19. set.removeAll(set1);
20. System.out.println("After invoking removeAll() method: "+set);
21. //Removing elements on the basis of specified condition
22. set.removeIf(str->str.contains("Vijay"));
23. System.out.println("After invoking removeIf() method: "+set);
24. //Removing all the elements available in the set
25. set.clear();
26. System.out.println("After invoking clear() method: "+set);
27. }
28. }
An initial list of elements: [Vijay, Ravi, Arun, Sumit]
After invoking remove(object) method: [Vijay, Arun, Sumit]
Updated List: [Vijay, Arun, Gaurav, Sumit, Ajay]
After invoking removeAll() method: [Vijay, Arun, Sumit]
After invoking removeIf() method: [Arun, Sumit]
After invoking clear() method: []

TreeSet
Java TreeSet class implements the Set interface that uses a tree for storage. Like HashSet, TreeSet
also contains unique elements. However, the access and retrieval time of TreeSet is quite fast. The
elements in TreeSet stored in ascending order.

Consider the following example:

1. import java.util.*;
2. public class TestJavaCollection9{
3. public static void main(String args[]){
4. //Creating and adding elements
5. TreeSet<String> set=new TreeSet<String>();
6. set.add("Ravi");
7. set.add("Vijay");
8. set.add("Ravi");
9. set.add("Ajay");
10. //traversing elements
11. Iterator<String> itr=set.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }
Output:

Ajay
Ravi
Vijay

List Interface

LIST INTERFACE
List interface is the child interface of Collection interface. It inhibits a list type data structure in which
we can store the ordered collection of objects. It can have duplicate values.

List interface is implemented by the classes ArrayList, LinkedList, Vector, and Stack.

To instantiate the List interface, we must use :

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


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

There are various methods in List interface that can be used to insert, delete, and access the elements
from the list.

The classes that implement the List interface are given below.

Java ArrayList class

Java ArrayList class uses a dynamic array for storing the elements. It inherits AbstractList class and
implements List interface.

The important points about Java ArrayList class are:

o Java ArrayList class can contain duplicate elements.


o Java ArrayList class maintains insertion order.
o Java ArrayList class is non synchronized.
o Java ArrayList allows random access because array works at the index basis.
o In Java ArrayList class, manipulation is slow because a lot of shifting needs to occur if any
element is removed from the array list.
Hierarchy of ArrayList class
As shown in the above diagram, Java ArrayList class extends AbstractList class which implements List
interface. The List interface extends the Collection and Iterable interfaces in hierarchical order.

ArrayList class declaration


Let's see the declaration for java.util.ArrayList class.

1. public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, C


loneable, Serializable

Constructors of Java ArrayList

Constructor Description

ArrayList() It is used to build an empty array list.

ArrayList(Collection<? extends E> It is used to build an array list that is initialized with the elements of the coll
c)
ArrayList(int capacity) It is used to build an array list that has the specified initial capacity.

Methods of Java ArrayList

Method Description

void add(int index, E element) It is used to insert the specified element at the specified
position in a list.

boolean add(E e) It is used to append the specified element at the end of


a list.

boolean addAll(Collection<? extends It is used to append all of the elements in the specified
E> c) collection to the end of this list, in the order that they
are returned by the specified collection's iterator.

boolean addAll(int index, It is used to append all the elements in the specified
Collection<? extends E> c) collection, starting at the specified position of the list.

void clear() It is used to remove all of the elements from this list.

void ensureCapacity(int It is used to enhance the capacity of an ArrayList


requiredCapacity) instance.

E get(int index) It is used to fetch the element from the particular


position of the list.

boolean isEmpty() It returns true if the list is empty, otherwise false.

int lastIndexOf(Object o) It is used to return the index in this list of the last
occurrence of the specified element, or -1 if the list does
not contain this element.

Object[] toArray() It is used to return an array containing all of the


elements in this list in the correct order.

<T> T[] toArray(T[] a) It is used to return an array containing all of the


elements in this list in the correct order.

Object clone() It is used to return a shallow copy of an ArrayList.

boolean contains(Object o) It returns true if the list contains the specified element

int indexOf(Object o) It is used to return the index in this list of the first
occurrence of the specified element, or -1 if the List
does not contain this element.

E remove(int index) It is used to remove the element present at the


specified position in the list.

boolean remove(Object o) It is used to remove the first occurrence of the specified


element.

boolean removeAll(Collection<?> c) It is used to remove all the elements from the list.

boolean removeIf(Predicate<? super It is used to remove all the elements from the list that
E> filter) satisfies the given predicate.

protected void removeRange(int It is used to remove all the elements lies within the
fromIndex, int toIndex) given range.

void replaceAll(UnaryOperator<E> It is used to replace all the elements from the list with
operator) the specified element.

void retainAll(Collection<?> c) It is used to retain all the elements in the list that are
present in the specified collection.

E set(int index, E element) It is used to replace the specified element in the list,
present at the specified position.
void sort(Comparator<? super E> c) It is used to sort the elements of the list on the basis of
specified comparator.

Spliterator<E> spliterator() It is used to create spliterator over the elements in a


list.

List<E> subList(int fromIndex, int It is used to fetch all the elements lies within the given
toIndex) range.

int size() It is used to return the number of elements present in


the list.

void trimToSize() It is used to trim the capacity of this ArrayList instance


to be the list's current size.

Java ArrayList Example


1. import java.util.*;
2. class ArrayList1{
3. public static void main(String args[]){
4. ArrayList<String> list=new ArrayList<String>();//Creating arraylist
5. list.add("Ravi");//Adding object in arraylist
6. list.add("Vijay");
7. list.add("Ravi");
8. list.add("Ajay");
9. //Invoking arraylist object
10. System.out.println(list);
11. }
12. }
13. }
[Ravi, Vijay, Ravi, Ajay]

Iterating Collection through Iterator interface


Let's see an example to traverse ArrayList elements using the Iterator interface.

1. import java.util.*;
2. class ArrayList2{
3. public static void main(String args[]){
4. ArrayList<String> list=new ArrayList<String>();//Creating arraylist
5. list.add("Ravi");//Adding object in arraylist
6. list.add("Vijay");
7. list.add("Ravi");
8. list.add("Ajay");
9. //Traversing list through Iterator
10. Iterator itr=list.iterator();
11. while(itr.hasNext()){
12. System.out.println(itr.next());
13. }
14. }
15. }
Test it Now

Ravi
Vijay
Ravi
Ajay

Iterating Collection through the for-each loop


Let's see an example to traverse the ArrayList elements using the for-each loop

1. import java.util.*;
2. class ArrayList3{
3. public static void main(String args[]){
4. ArrayList<String> al=new ArrayList<String>();
5. al.add("Ravi");
6. al.add("Vijay");
7. al.add("Ravi");
8. al.add("Ajay");
9. //Traversing list through for-each loop
10. for(String obj:al)
11. System.out.println(obj);
12. }
13. }
Ravi
Vijay
Ravi
Ajay

Java LinkedList class

Java LinkedList class uses a doubly linked list to store the elements. It provides a linked-list data
structure. It inherits the AbstractList class and implements List and Deque interfaces.

The important points about Java LinkedList are:

o Java LinkedList class can contain duplicate elements.


o Java LinkedList class maintains insertion order.
o Java LinkedList class is non synchronized.
o In Java LinkedList class, manipulation is fast because no shifting needs to occur.
o Java LinkedList class can be used as a list, stack or queue.

Hierarchy of LinkedList class


As shown in the above diagram, Java LinkedList class extends AbstractSequentialList class and
implements List and Deque interfaces.
Doubly Linked List
In the case of a doubly linked list, we can add or remove elements from both sides.

LinkedList class declaration


Let's see the declaration for java.util.LinkedList class.

1. public class LinkedList<E> extends AbstractSequentialList<E> implements List<E>, Dequ


e<E>, Cloneable, Serializable

Constructors of Java LinkedList

Constructor Description

LinkedList() It is used to construct an empty list.

LinkedList(Collection<? extends It is used to construct a list containing the elements of the specified collection, in
E> c) order, they are returned by the collection's iterator.
Methods of Java LinkedList

Method Description

boolean add(E e) It is used to append the specified element to the end of a


list.

void add(int index, E element) It is used to insert the specified element at the specified
position index in a list.

boolean addAll(Collection<? extends It is used to append all of the elements in the specified
E> c) collection to the end of this list, in the order that they are
returned by the specified collection's iterator.

boolean addAll(Collection<? extends It is used to append all of the elements in the specified
E> c) collection to the end of this list, in the order that they are
returned by the specified collection's iterator.

boolean addAll(int index, It is used to append all the elements in the specified
Collection<? extends E> c) collection, starting at the specified position of the list.

void addFirst(E e) It is used to insert the given element at the beginning of


a list.

void addLast(E e) It is used to append the given element to the end of a


list.

void clear() It is used to remove all the elements from a list.

Object clone() It is used to return a shallow copy of an ArrayList.

boolean contains(Object o) It is used to return true if a list contains a specified


element.

Iterator<E> descendingIterator() It is used to return an iterator over the elements in a


deque in reverse sequential order.

E element() It is used to retrieve the first element of a list.

E get(int index) It is used to return the element at the specified position


in a list.

E getFirst() It is used to return the first element in a list.

E getLast() It is used to return the last element in a list.

int indexOf(Object o) It is used to return the index in a list of the first


occurrence of the specified element, or -1 if the list does
not contain any element.

int lastIndexOf(Object o) It is used to return the index in a list of the last


occurrence of the specified element, or -1 if the list does
not contain any element.

ListIterator<E> listIterator(int It is used to return a list-iterator of the elements in


index) proper sequence, starting at the specified position in the
list.

boolean offer(E e) It adds the specified element as the last element of a list.

boolean offerFirst(E e) It inserts the specified element at the front of a list.

boolean offerLast(E e) It inserts the specified element at the end of a list.

E peek() It retrieves the first element of a list

E peekFirst() It retrieves the first element of a list or returns null if a


list is empty.

E peekLast() It retrieves the last element of a list or returns null if a


list is empty.

E poll() It retrieves and removes the first element of a list.

E pollFirst() It retrieves and removes the first element of a list, or


returns null if a list is empty.

E pollLast() It retrieves and removes the last element of a list, or


returns null if a list is empty.

E pop() It pops an element from the stack represented by a list.

void push(E e) It pushes an element onto the stack represented by a


list.

E remove() It is used to retrieve and removes the first element of a


list.

E remove(int index) It is used to remove the element at the specified position


in a list.

boolean remove(Object o) It is used to remove the first occurrence of the specified


element in a list.

E removeFirst() It removes and returns the first element from a list.

boolean It is used to remove the first occurrence of the specified


removeFirstOccurrence(Object o) element in a list (when traversing the list from head to
tail).

E removeLast() It removes and returns the last element from a list.

boolean It removes the last occurrence of the specified element in


removeLastOccurrence(Object o) a list (when traversing the list from head to tail).
E set(int index, E element) It replaces the element at the specified position in a list
with the specified element.

Object[] toArray() It is used to return an array containing all the elements


in a list in proper sequence (from first to the last
element).

<T> T[] toArray(T[] a) It returns an array containing all the elements in the
proper sequence (from first to the last element); the
runtime type of the returned array is that of the specified
array.

int size() It is used to return the number of elements in a list.

Java LinkedList Example

1. import java.util.*;
2. public class LinkedList1{
3. public static void main(String args[]){
4.
5. LinkedList<String> al=new LinkedList<String>();
6. al.add("Ravi");
7. al.add("Vijay");
8. al.add("Ravi");
9. al.add("Ajay");
10.
11. Iterator<String> itr=al.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }

Output: Ravi
Vijay
Ravi
Ajay
Java LinkedList example to remove elements
1. mport java.util.*;
2. public class LinkedList3 {
3.
4. public static void main(String [] args)
5. {
6. LinkedList<String> ll=new LinkedList<String>();
7. ll.add("Ravi");
8. ll.add("Vijay");
9. ll.add("Ajay");
10. ll.add("Anuj");
11. ll.add("Gaurav");
12. ll.add("Harsh");
13. ll.add("Virat");
14. ll.add("Gaurav");
15. ll.add("Harsh");
16. ll.add("Amit");
17. System.out.println("Initial list of elements: "+ll);
18. //Removing specific element from arraylist
19. ll.remove("Vijay");
20. System.out.println("After invoking remove(object) method: "+ll);
21. //Removing element on the basis of specific position
22. ll.remove(0);
23. System.out.println("After invoking remove(index) method: "+ll);
24. LinkedList<String> ll2=new LinkedList<String>();
25. ll2.add("Ravi");
26. ll2.add("Hanumat");
27. // Adding new elements to arraylist
28. ll.addAll(ll2);
29. System.out.println("Updated list : "+ll);
30. //Removing all the new elements from arraylist
31. ll.removeAll(ll2);
32. System.out.println("After invoking removeAll() method: "+ll);
33. //Removing first element from the list
34. ll.removeFirst();
35. System.out.println("After invoking removeFirst() method: "+ll);
36. //Removing first element from the list
37. ll.removeLast();
38. System.out.println("After invoking removeLast() method: "+ll);
39. //Removing first occurrence of element from the list
40. ll.removeFirstOccurrence("Gaurav");
41. System.out.println("After invoking removeFirstOccurrence() method: "+ll);
42. //Removing last occurrence of element from the list
43. ll.removeLastOccurrence("Harsh");
44. System.out.println("After invoking removeLastOccurrence() method: "+ll);
45.
46. //Removing all the elements available in the list
47. ll.clear();
48. System.out.println("After invoking clear() method: "+ll);
49. }
50. }
Initial list of elements: [Ravi, Vijay, Ajay, Anuj, Gaurav, Harsh, Virat,
Gaurav, Harsh, Amit]
After invoking remove(object) method: [Ravi, Ajay, Anuj, Gaurav, Harsh, Virat,
Gaurav, Harsh, Amit]
After invoking remove(index) method: [Ajay, Anuj, Gaurav, Harsh, Virat,
Gaurav, Harsh, Amit]
Updated list : [Ajay, Anuj, Gaurav, Harsh, Virat, Gaurav, Harsh, Amit, Ravi,
Hanumat]
After invoking removeAll() method: [Ajay, Anuj, Gaurav, Harsh, Virat, Gaurav,
Harsh, Amit]
After invoking removeFirst() method: [Gaurav, Harsh, Virat, Gaurav, Harsh,
Amit]
After invoking removeLast() method: [Gaurav, Harsh, Virat, Gaurav, Harsh]
After invoking removeFirstOccurrence() method: [Harsh, Virat, Gaurav, Harsh]
After invoking removeLastOccurrence() method: [Harsh, Virat, Gaurav]
After invoking clear() method: []

Java LinkedList Example to reverse a list of elements


1. import java.util.*;
2. public class LinkedList4{
3. public static void main(String args[]){
4.
5. LinkedList<String> ll=new LinkedList<String>();
6. ll.add("Ravi");
7. ll.add("Vijay");
8. ll.add("Ajay");
9. //Traversing the list of elements in reverse order
10. Iterator i=ll.descendingIterator();
11. while(i.hasNext())
12. {
13. System.out.println(i.next());
14. }
15.
16. }
17. }
Output: Ajay
Vijay
Ravi
Queue Interface
Queue interface maintains the first-in-first-out order. It can be defined as an ordered list that is used
to hold the elements which are about to be processed. There are various classes like PriorityQueue,
Deque, and ArrayDeque which implements the Queue interface.

Queue interface can be instantiated as:

1. Queue<String> q1 = new PriorityQueue();


2. Queue<String> q2 = new ArrayDeque();

There are various classes that implement the Queue interface, some of them are given below.

PriorityQueue
The PriorityQueue class implements the Queue interface. It holds the elements or objects which are to
be processed by their priorities. PriorityQueue doesn't allow null values to be stored in the queue.

Consider the following example.

1. import java.util.*;
2. public class TestJavaCollection5{
3. public static void main(String args[]){
4. PriorityQueue<String> queue=new PriorityQueue<String>();
5. queue.add("Amit Sharma");
6. queue.add("Vijay Raj");
7. queue.add("JaiShankar");
8. queue.add("Raj");
9. System.out.println("head:"+queue.element());
10. System.out.println("head:"+queue.peek());
11. System.out.println("iterating the queue elements:");
12. Iterator itr=queue.iterator();
13. while(itr.hasNext()){
14. System.out.println(itr.next());
15. }
16. queue.remove();
17. queue.poll();
18. System.out.println("after removing two elements:");
19. Iterator<String> itr2=queue.iterator();
20. while(itr2.hasNext()){
21. System.out.println(itr2.next());
22. }
23. }
24. }
Output:

head:Amit Sharma
head:Amit Sharma
iterating the queue elements:
Amit Sharma
Raj
JaiShankar
Vijay Raj
after removing two elements:
Raj
Vijay Raj

Deque Interface
Deque interface extends the Queue interface. In Deque, we can remove and add the elements from
both the side. Deque stands for a double-ended queue which enables us to perform the operations at
both the ends.

Deque can be instantiated as:

1. Deque d = new ArrayDeque();

ArrayDeque
ArrayDeque class implements the Deque interface. It facilitates us to use the Deque. Unlike queue, we
can add or delete the elements from both the ends.

ArrayDeque is faster than ArrayList and Stack and has no capacity restrictions.

Consider the following example.

1. import java.util.*;
2. public class TestJavaCollection6{
3. public static void main(String[] args) {
4. //Creating Deque and adding elements
5. Deque<String> deque = new ArrayDeque<String>();
6. deque.add("Gautam");
7. deque.add("Karan");
8. deque.add("Ajay");
9. //Traversing elements
10. for (String str : deque) {
11. System.out.println(str);
12. }
13. }
14. }

Output:
Gautam
Karan
Ajay

You might also like