Collections in Java2
Collections in Java2
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.
Let us see the hierarchy of Collection framework. The java.util package contains all
the classes and interfaces for the Collection framework.
Methods of Collection interface
There are many methods declared in the Collection interface. They are as follows:
No Method Description
.
6 public int size() It returns the total number of elements in the collection.
7 public void clear() It removes the total number of elements from the
collection.
import java.io.*;
import java.util.*;
Iterator interface
Iterator interface provides the facility of iterating the elements in a forward direction only.
There are only three methods in the Iterator interface. They are:
No Method Description
.
1 public boolean It returns true if the iterator has more elements otherwise it returns
hasNext() false.
2 public Object next() It returns the element and moves the cursor pointer to the next
element.
3 public void remove() It removes the last elements returned by the iterator. It is less used.
Iterable Interface
The Iterable interface is the root interface for all the collection classes. The Collection
interface extends the Iterable interface and therefore all the subclasses of Collection interface
also implement the Iterable interface.
1. Iterator<T> iterator()
The Collection interface is the interface which is implemented by all the classes in the
collection framework. It declares the methods that every collection will have. In other words,
we can say that the Collection interface builds the foundation on which the collection
framework depends.
Some of the methods of Collection interface are Boolean add ( Object obj), Boolean addAll
( Collection c), void clear(), etc. which are implemented by all the subclasses of Collection
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.
There are various methods in List interface that can be used to insert, delete, and access the
elements from the list.
Java ArrayList
Java ArrayList class uses a dynamic array for storing the elements. It is like an array, but
there is no size limit. We can add or remove elements anytime. So, it is much more flexible
than the traditional array. It is found in the java.util package. It is like the Vector in C++.
FileName: ArrayListExample1.java
1. import java.util.*;
2. public class ArrayListExample1{
3. public static void main(String args[]){
4. ArrayList<String> list=new ArrayList<String>();//Creating arraylist
5. list.add("Mango");//Adding object in arraylist
6. list.add("Apple");
7. list.add("Banana");
8. list.add("Grapes");
9. //Printing the arraylist object
10. System.out.println(list);
11. }
12. }
Output:
Let's see an example to traverse ArrayList elements using the Iterator interface.
FileName: ArrayListExample2.java
1. import java.util.*;
2. public class ArrayListExample2{
3. public static void main(String args[]){
4. ArrayList<String> list=new ArrayList<String>();//Creating arraylist
5. list.add("Mango");//Adding object in arraylist
6. list.add("Apple");
7. list.add("Banana");
8. list.add("Grapes");
9. //Traversing list through Iterator
10. Iterator itr=list.iterator();//getting the Iterator
11. while(itr.hasNext()){//check if iterator has the elements
12. System.out.println(itr.next());//printing the element and move to next
13. }
14. }
15. }
Output:
Mango
Apple
Banana
Grapes
Iterating ArrayList using For-each loop
Let's see an example to traverse the ArrayList elements using the for-each loop
FileName: ArrayListExample3.java
1. import java.util.*;
2. public class ArrayListExample3{
3. public static void main(String args[]){
4. ArrayList<String> list=new ArrayList<String>();//Creating arraylist
5. list.add("Mango");//Adding object in arraylist
6. list.add("Apple");
7. list.add("Banana");
8. list.add("Grapes");
9. //Traversing list through for-each loop
10. for(String fruit:list)
11. System.out.println(fruit);
12.
13. }
14. }
Output:
Mango
Apple
Banana
Grapes
Get and Set ArrayList
The get() method returns the element at the specified index, whereas the set() method changes
the element.
FileName: ArrayListExample4.java
1. import java.util.*;
2. public class ArrayListExample4{
3. public static void main(String args[]){
4. ArrayList<String> al=new ArrayList<String>();
5. al.add("Mango");
6. al.add("Apple");
7. al.add("Banana");
8. al.add("Grapes");
9. //accessing the element
10. System.out.println("Returning element: "+al.get(1));//it will return the 2nd element,
because index starts from 0
11. //changing the element
12. al.set(1,"Dates");
13. //Traversing list
14. for(String fruit:al)
15. System.out.println(fruit);
16.
17. }
18. }
Test it Now
Output:
The java.util package provides a utility class Collections, which has the static method sort().
Using the Collections.sort() method, we can easily sort the ArrayList.
FileName: SortArrayList.java
1. import java.util.*;
2. class SortArrayList{
3. public static void main(String args[]){
4. //Creating a list of fruits
5. List<String> list1=new ArrayList<String>();
6. list1.add("Mango");
7. list1.add("Apple");
8. list1.add("Banana");
9. list1.add("Grapes");
10. //Sorting the list
11. Collections.sort(list1);
12. //Traversing list through the for-each loop
13. for(String fruit:list1)
14. System.out.println(fruit);
15.
16. System.out.println("Sorting numbers...");
17. //Creating a list of numbers
18. List<Integer> list2=new ArrayList<Integer>();
19. list2.add(21);
20. list2.add(11);
21. list2.add(51);
22. list2.add(1);
23. //Sorting the list
24. Collections.sort(list2);
25. //Traversing list through the for-each loop
26. for(Integer number:list2)
27. System.out.println(number);
28. }
29.
30. }
Output:
Apple
Banana
Grapes
Mango
Sorting numbers...
1
11
21
51
Ways to iterate the elements of the collection in Java
1. By Iterator interface.
2. By for-each loop.
3. By ListIterator interface.
4. By for loop.
5. By forEach() method.
6. By forEachRemaining() method.
Let's see an example to traverse the ArrayList elements through other ways
ADVERTISEMENT
FileName: ArrayList4.java
1. import java.util.*;
2. class ArrayList4{
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.
10. System.out.println("Traversing list through List Iterator:");
11. //Here, element iterates in reverse order
12. ListIterator<String> list1=list.listIterator(list.size());
13. while(list1.hasPrevious())
14. {
15. String str=list1.previous();
16. System.out.println(str);
17. }
18. System.out.println("Traversing list through for loop:");
19. for(int i=0;i<list.size();i++)
20. {
21. System.out.println(list.get(i));
22. }
23.
24. System.out.println("Traversing list through forEach() method:");
25. //The forEach() method is a new feature, introduced in Java 8.
26. list.forEach(a->{ //Here, we are using lambda expression
27. System.out.println(a);
28. });
29.
30. System.out.println("Traversing list through forEachRemaining() method:");
31. Iterator<String> itr=list.iterator();
32. itr.forEachRemaining(a-> //Here, we are using lambda expression
33. {
34. System.out.println(a);
35. });
36. }
37. }
Output:
Let's see an example where we are storing Student class object in an array list.
FileName: ArrayList5.java
1. class Student{
2. int rollno;
3. String name;
4. int age;
5. Student(int rollno,String name,int age){
6. this.rollno=rollno;
7. this.name=name;
8. this.age=age;
9. }
10. }
1. import java.util.*;
2. class ArrayList5{
3. public static void main(String args[]){
4. //Creating user-defined class objects
5. Student s1=new Student(101,"Sonoo",23);
6. Student s2=new Student(102,"Ravi",21);
7. Student s2=new Student(103,"Hanumat",25);
8. //creating arraylist
9. ArrayList<Student> al=new ArrayList<Student>();
10. al.add(s1);//adding Student class object
11. al.add(s2);
12. al.add(s3);
13. //Getting Iterator
14. Iterator itr=al.iterator();
15. //traversing elements of ArrayList object
16. while(itr.hasNext()){
17. Student st=(Student)itr.next();
18. System.out.println(st.rollno+" "+st.name+" "+st.age);
19. }
20. }
21. }
Output:
101 Sonoo 23
102 Ravi 21
103 Hanumat 25
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.
In the case of a doubly linked list, we can add or remove elements from both sides.
1. import java.util.*;
2. public class LinkedList2{
3. public static void main(String args[]){
4. LinkedList<String> ll=new LinkedList<String>();
5. System.out.println("Initial list of elements: "+ll);
6. ll.add("Ravi");
7. ll.add("Vijay");
8. ll.add("Ajay");
9. System.out.println("After invoking add(E e) method: "+ll);
10. //Adding an element at the specific position
11. ll.add(1, "Gaurav");
12. System.out.println("After invoking add(int index, E element) method: "+ll);
13. LinkedList<String> ll2=new LinkedList<String>();
14. ll2.add("Sonoo");
15. ll2.add("Hanumat");
16. //Adding second list elements to the first list
17. ll.addAll(ll2);
18. System.out.println("After invoking addAll(Collection<? extends E> c) method:
"+ll);
19. LinkedList<String> ll3=new LinkedList<String>();
20. ll3.add("John");
21. ll3.add("Rahul");
22. //Adding second list elements to the first list at specific position
23. ll.addAll(1, ll3);
24. System.out.println("After invoking addAll(int index, Collection<? extends E>
c) method: "+ll);
25. //Adding an element at the first position
26. ll.addFirst("Lokesh");
27. System.out.println("After invoking addFirst(E e) method: "+ll);
28. //Adding an element at the last position
29. ll.addLast("Harsh");
30. System.out.println("After invoking addLast(E e) method: "+ll);
31.
32. }
33. }
Initial list of elements: []
After invoking add(E e) method: [Ravi, Vijay, Ajay]
After invoking add(int index, E element) method: [Ravi, Gaurav, Vijay, Ajay]
After invoking addAll(Collection<? extends E> c) method:
[Ravi, Gaurav, Vijay, Ajay, Sonoo, Hanumat]
After invoking addAll(int index, Collection<? extends E> c) method:
[Ravi, John, Rahul, Gaurav, Vijay, Ajay, Sonoo, Hanumat]
After invoking addFirst(E e) method:
[Lokesh, Ravi, John, Rahul, Gaurav, Vijay, Ajay, Sonoo, Hanumat]
After invoking addLast(E e) method:
[Lokesh, Ravi, John, Rahul, Gaurav, Vijay, Ajay, Sonoo, Hanumat, Harsh]
1. import 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: []
Output:
Vector is like the dynamic array which can grow or shrink its size. Unlike array, we can
store n-number of elements in it as there is no size limit. It is a part of Java Collection
framework since Java 1.2. It is found in the java.util package and implements
the List interface, so we can use all the methods of List interface here.
It is recommended to use the Vector class in the thread-safe implementation only. If you don't
need to use the thread-safe implementation, you should use the ArrayList, the ArrayList will
perform better in such case.
Java Vector Example
1. import java.util.*;
2. public class VectorExample {
3. public static void main(String args[]) {
4. //Create a vector
5. Vector<String> vec = new Vector<String>();
6. //Adding elements using add() method of List
7. vec.add("Tiger");
8. vec.add("Lion");
9. vec.add("Dog");
10. vec.add("Elephant");
11. //Adding elements using addElement() method of Vector
12. vec.addElement("Rat");
13. vec.addElement("Cat");
14. vec.addElement("Deer");
15.
16. System.out.println("Elements are: "+vec);
17. }
18. }
Output:
Output:
Size is: 4
Default capacity is: 4
Vector element is: [Tiger, Lion, Dog, Elephant]
Size after addition: 7
Capacity after addition is: 8
Elements are: [Tiger, Lion, Dog, Elephant, Rat, Cat, Deer]
Tiger is present at the index 0
The first animal of the vector is = Tiger
The last animal of the vector is = Deer
Java Vector Example 3
1. import java.util.*;
2. public class VectorExample2 {
3. public static void main(String args[]) {
4. //Create an empty Vector
5. Vector<Integer> in = new Vector<>();
6. //Add elements in the vector
7. in.add(100);
8. in.add(200);
9. in.add(300);
10. in.add(200);
11. in.add(400);
12. in.add(500);
13. in.add(600);
14. in.add(700);
15. //Display the vector elements
16. System.out.println("Values in vector: " +in);
17. //use remove() method to delete the first occurence of an element
18. System.out.println("Remove first occourence of element 200: "+in.remove((Inte
ger)200));
19. //Display the vector elements afre remove() method
20. System.out.println("Values in vector: " +in);
21. //Remove the element at index 4
22. System.out.println("Remove element at index 4: " +in.remove(4));
23. System.out.println("New Value list in vector: " +in);
24. //Remove an element
25. in.removeElementAt(5);
26. //Checking vector and displays the element
27. System.out.println("Vector element after removal: " +in);
28. //Get the hashcode for this vector
29. System.out.println("Hash code of this vector = "+in.hashCode());
30. //Get the element at specified index
31. System.out.println("Element at index 1 is = "+in.get(1));
32. }
33. }
Output:
Values in vector: [100, 200, 300, 200, 400, 500, 600, 700]
Remove first occourence of element 200: true
Values in vector: [100, 300, 200, 400, 500, 600, 700]
Remove element at index 4: 500
New Value list in vector: [100, 300, 200, 400, 600, 700]
Vector element after removal: [100, 300, 200, 400, 600]
Hash code of this vector = 130123751
Element at index 1 is = 300
In Java, Stack is a class that falls under the Collection framework that extends
the Vector class. It also implements interfaces List, Collection, Iterable, Cloneable,
Serializable. It represents the LIFO stack of objects. Before using the Stack class, we must
import the java.util package. The stack class arranged in the Collections framework
hierarchy, as shown below.
The Stack class contains only the default constructor that creates an empty stack.
1. public Stack()
Creating a Stack
If we want to create a stack, first, import the java.util package and create an object of the
Stack class.
Or
Where type denotes the type of stack like Integer, String, etc.
We can perform push, pop, peek and search operation on the stack. The Java Stack class
provides mainly five methods to perform these operations. Along with this, it also provides
all the methods of the Java Vector class.
push(E item) E The method pushes (insert) an element onto the top of the stack.
pop() E The method removes an element from the top of the stack and
returns the same element as the value of that function.
peek() E The method looks at the top element of the stack without removing
it.
search(Object int The method searches the specified object and returns the position of
o) the object.
The empty() method of the Stack class check the stack is empty or not. If the stack is empty,
it returns true, else returns false. We can also use the isEmpty() method of the Vector class.
Syntax
In the following example, we have created an instance of the Stack class. After that, we have
invoked the empty() method two times. The first time it returns true because we have not
pushed any element into the stack. After that, we have pushed elements into the stack. Again
we have invoked the empty() method that returns false because the stack is not empty.
StackEmptyMethodExample.java
1. import java.util.Stack;
2. public class StackEmptyMethodExample
3. {
4. public static void main(String[] args)
5. {
6. //creating an instance of Stack class
7. Stack<Integer> stk= new Stack<>();
8. // checking stack is empty or not
9. boolean result = stk.empty();
10. System.out.println("Is the stack empty? " + result);
11. // pushing elements into stack
12. stk.push(78);
13. stk.push(113);
14. stk.push(90);
15. stk.push(120);
16. //prints elements of the stack
17. System.out.println("Elements in Stack: " + stk);
18. result = stk.empty();
19. System.out.println("Is the stack empty? " + result);
20. }
21. }
Output:
The method inserts an item onto the top of the stack. It works the same as the
method addElement(item) method of the Vector class. It passes a parameter item to be
pushed into the stack.
Syntax
Returns: The method returns the argument that we have passed as a parameter.
The method removes an object at the top of the stack and returns the same object. It
throws EmptyStackException if the stack is empty.
Syntax
1. public E pop()
Let's implement the stack in a Java program and perform push and pop operations.
StackPushPopExample.java
1. import java.util.*;
2. public class StackPushPopExample
3. {
4. public static void main(String args[])
5. {
6. //creating an object of Stack class
7. Stack <Integer> stk = new Stack<>();
8. System.out.println("stack: " + stk);
9. //pushing elements into the stack
10. pushelmnt(stk, 20);
11. pushelmnt(stk, 13);
12. pushelmnt(stk, 89);
13. pushelmnt(stk, 90);
14. pushelmnt(stk, 11);
15. pushelmnt(stk, 45);
16. pushelmnt(stk, 18);
17. //popping elements from the stack
18. popelmnt(stk);
19. popelmnt(stk);
20. //throws exception if the stack is empty
21. try
22. {
23. popelmnt(stk);
24. }
25. catch (EmptyStackException e)
26. {
27. System.out.println("empty stack");
28. }
29. }
30. //performing push operation
31. static void pushelmnt(Stack stk, int x)
32. {
33. //invoking push() method
34. stk.push(new Integer(x));
35. System.out.println("push -> " + x);
36. //prints modified stack
37. System.out.println("stack: " + stk);
38. }
39. //performing pop operation
40. static void popelmnt(Stack stk)
41. {
42. System.out.print("pop -> ");
43. //invoking pop() method
44. Integer x = (Integer) stk.pop();
45. System.out.println(x);
46. //prints modified stack
47. System.out.println("stack: " + stk);
48. }
49. }
Output:
stack: []
push -> 20
stack: [20]
push -> 13
stack: [20, 13]
push -> 89
stack: [20, 13, 89]
push -> 90
stack: [20, 13, 89, 90]
push -> 11
stack: [20, 13, 89, 90, 11]
push -> 45
stack: [20, 13, 89, 90, 11, 45]
push -> 18
stack: [20, 13, 89, 90, 11, 45, 18]
pop -> 18
stack: [20, 13, 89, 90, 11, 45]
pop -> 45
stack: [20, 13, 89, 90, 11]
pop -> 11
stack: [20, 13, 89, 90]
Stack Class peek() Method
It looks at the element that is at the top in the stack. It also throws EmptyStackException if
the stack is empty.
Syntax
1. public E peek()
StackPeekMethodExample.java
1. import java.util.Stack;
2. public class StackPeekMethodExample
3. {
4. public static void main(String[] args)
5. {
6. Stack<String> stk= new Stack<>();
7. // pushing elements into Stack
8. stk.push("Apple");
9. stk.push("Grapes");
10. stk.push("Mango");
11. stk.push("Orange");
12. System.out.println("Stack: " + stk);
13. // Access element from the top of the stack
14. String fruits = stk.peek();
15. //prints stack
16. System.out.println("Element at top: " + fruits);
17. }
18. }
Output:
The method searches the object in the stack from the top. It parses a parameter that we want
to search for. It returns the 1-based location of the object in the stack. Thes topmost object of
the stack is considered at distance 1.
Suppose, o is an object in the stack that we want to search for. The method returns the
distance from the top of the stack of the occurrence nearest the top of the stack. It
uses equals() method to search an object in the stack.
Syntax
Returns: It returns the object location from the top of the stack. If it returns -1, it means that
the object is not on the stack.
StackSearchMethodExample.java
1. import java.util.Stack;
2. public class StackSearchMethodExample
3. {
4. public static void main(String[] args)
5. {
6. Stack<String> stk= new Stack<>();
7. //pushing elements into Stack
8. stk.push("Mac Book");
9. stk.push("HP");
10. stk.push("DELL");
11. stk.push("Asus");
12. System.out.println("Stack: " + stk);
13. // Search an element
14. int location = stk.search("HP");
15. System.out.println("Location of Dell: " + location);
16. }
17. }
Java Stack Operations
Size of the Stack
We can also find the size of the stack using the size() method of the Vector class. It returns
the total number of elements (size of the stack) in the stack.
Syntax
StackSizeExample.java
1. import java.util.Stack;
2. public class StackSizeExample
3. {
4. public static void main (String[] args)
5. {
6. Stack stk = new Stack();
7. stk.push(22);
8. stk.push(33);
9. stk.push(44);
10. stk.push(55);
11. stk.push(66);
12. // Checks the Stack is empty or not
13. boolean rslt=stk.empty();
14. System.out.println("Is the stack empty or not? " +rslt);
15. // Find the size of the Stack
16. int x=stk.size();
17. System.out.println("The stack size is: "+x);
18. }
19. }
Example:
Java
import java.util.LinkedList;
import java.util.Queue;
Output
Queue: [apple, banana, cherry]
Removed element: apple
Queue after removal: [banana, cherry]
Peeked element: banana
Queue after peek: [banana, cherry, date]
Example: Queue
Java
import java.util.LinkedList;
import java.util.Queue;
System.out.println(q);
Output
Elements of queue [0, 1, 2, 3, 4]
removed element-0
[1, 2, 3, 4]
head of queue-1
Size of queue-4
Operations on Queue Interface
Let’s see how to perform a few frequently used operations on the queue using the Priority
Queue class.
1. Adding Elements: In order to add an element in a queue, we can use the add() method.
The insertion order is not retained in the PriorityQueue. The elements are stored based on
the priority order which is ascending by default.
Example
Java
import java.util.*;
pq.add("Geeks");
pq.add("For");
pq.add("Geeks");
System.out.println(pq);
}
}
Output
[For, Geeks, Geeks]
2. Removing Elements: In order to remove an element from a queue, we can use
the remove() method. If there are multiple such objects, then the first occurrence of the
object is removed. Apart from that, poll() method is also used to remove the head and
return it.
Example
Java
import java.util.*;
pq.add("Geeks");
pq.add("For");
pq.add("Geeks");
pq.remove("Geeks");
import java.util.*;
pq.add("Geeks");
pq.add("For");
pq.add("Geeks");
while (iterator.hasNext()) {
System.out.print(iterator.next() + " ");
}
}
}
FileName: ArrayDequeExample.java
1. import java.util.*;
2. public class ArrayDequeExample {
3. public static void main(String[] args) {
4. //Creating Deque and adding elements
5. Deque<String> deque = new ArrayDeque<String>();
6. deque.add("Ravi");
7. deque.add("Vijay");
8. deque.add("Ajay");
9. //Traversing elements
10. for (String str : deque) {
11. System.out.println(str);
12. }
13. }
14. }
Output:
Ravi
Vijay
Ajay
Java ArrayDeque Example: offerFirst() and pollLast()
FileName: DequeExample.java
1. import java.util.*;
2. public class DequeExample {
3. public static void main(String[] args) {
4. Deque<String> deque=new ArrayDeque<String>();
5. deque.offer("arvind");
6. deque.offer("vimal");
7. deque.add("mukul");
8. deque.offerFirst("jai");
9. System.out.println("After offerFirst Traversal...");
10. for(String s:deque){
11. System.out.println(s);
12. }
13. //deque.poll();
14. //deque.pollFirst();//it is same as poll()
15. deque.pollLast();
16. System.out.println("After pollLast() Traversal...");
17. for(String s:deque){
18. System.out.println(s);
19. }
20. }
21. }
Output:
FileName: ArrayDequeExample.java
1. import java.util.*;
2. class Book {
3. int id;
4. String name,author,publisher;
5. int quantity;
6. public Book(int id, String name, String author, String publisher, int quantity) {
7. this.id = id;
8. this.name = name;
9. this.author = author;
10. this.publisher = publisher;
11. this.quantity = quantity;
12. }
13. }
14. public class ArrayDequeExample {
15. public static void main(String[] args) {
16. Deque<Book> set=new ArrayDeque<Book>();
17. //Creating Books
18. Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
19. Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc
Graw Hill",4);
20. Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
21. //Adding Books to Deque
22. set.add(b1);
23. set.add(b2);
24. set.add(b3);
25. //Traversing ArrayDeque
26. for(Book b:set){
27. System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);
28. }
29. }
30. }
Output:
SetExample1.java
1. import java.util.*;
2. public class setExample{
3. public static void main(String[] args)
4. {
5. // creating LinkedHashSet using the Set
6. Set<String> data = new LinkedHashSet<String>();
7.
8. data.add("JavaTpoint");
9. data.add("Set");
10. data.add("Example");
11. data.add("Set");
12.
13. System.out.println(data);
14. }
15. }
Output:
Note: Throughout the section, we have compiled the program with file name and
run the program with class name. Because the file name and the class name are
different.
Suppose, we have two sets, i.e., set1 = [22, 45, 33, 66, 55, 34, 77] and
set2 = [33, 2, 83, 45, 3, 12, 55]. We can perform the following operation
on the Set:
SetExample2.java
1. import java.util.*;
2. public class SetOperations
3. {
4. public static void main(String args[])
5. {
6. Integer[] A = {22, 45,33, 66, 55, 34, 77};
7. Integer[] B = {33, 2, 83, 45, 3, 12, 55};
8. Set<Integer> set1 = new HashSet<Integer>();
9. set1.addAll(Arrays.asList(A));
10. Set<Integer> set2 = new HashSet<Integer>();
11. set2.addAll(Arrays.asList(B));
12.
13. // Finding Union of set1 and set2
14. Set<Integer> union_data = new HashSet<Integer>(set1);
15. union_data.addAll(set2);
16. System.out.print("Union of set1 and set2 is:");
17. System.out.println(union_data);
18.
19. // Finding Intersection of set1 and set2
20. Set<Integer> intersection_data = new HashSet<Integer>(set1);
21. intersection_data.retainAll(set2);
22. System.out.print("Intersection of set1 and set2 is:");
23. System.out.println(intersection_data);
24.
25. // Finding Difference of set1 and set2
26. Set<Integer> difference_data = new HashSet<Integer>(set1);
27. difference_data.removeAll(set2);
28. System.out.print("Difference of set1 and set2 is:");
29. System.out.println(difference_data);
30. }
31. }
Output:
Description:
In the above code, first, we create two arrays, i.e., A and B of type integer.
After that, we create two set, i.e., set1 and set2 of type integer. We
convert both the array into a list and add the elements of array A into set1
and elements of array B into set2.
For performing the union, we create a new set union_data with the same
element of the set1. We then call the addAll() method of set and pass the
set2 as an argument to it. This method will add all those elements to
the union_data which are not present in it and gives the union of both
sets.
Set Methods
There are several methods available in the set interface which we can use
to perform a certain operation on our sets. These methods are as follows:
1) add()
The add() method insert a new value to the set. The method returns true
and false depending on the presence of the insertion element. It returns
false if the element is already present in the set and returns true if it is
not present in the set.
Syntax:
SetExample3.java
1. import java.io.*;
2. import java.util.*;
3. public class addMethod {
4. public static void main(String args[])
5. {
6. Set<Integer> data = new LinkedHashSet<Integer>();
7. data.add(31);
8. data.add(21);
9. data.add(41);
10. data.add(11);
11. data.add(61);
12. data.add(51);
13. System.out.println("data: " + data);
14. }
15. }
Output:
2) addAll()
The addAll() method appends all the elements of the specified collection
to the set.
Syntax:
SetExample4.java
1. import java.io.*;
2. import java.util.*;
3. class addAllMethod {
4. public static void main(String args[])
5. {
6. Set<Integer> data = new LinkedHashSet<Integer>();
7. data.add(31);
8. data.add(21);
9. data.add(41);
10. System.out.println("Set: " + data);
11. ArrayList<Integer> newData = new ArrayList<Integer>(
);
12. newData.add(91);
13. newData.add(71);
14. newData.add(81);
15. data.addAll(newData);
16. System.out.println("Set: " + data);
17. }
18.}
Output:
3) clear()
The method removes all the elements from the set. It doesn't delete the
reference of the set. It only deletes the elements of the set.
Syntax:
Output:
4) contains()
The contains() method is used to know the presence of an element in the
set. Its return value is true or false depending on the presence of the
element.
Syntax:
SetExample6.java
1. import java.io.*;
2. import java.util.*;
3. class containsMethod {
4. public static void main(String args[])
5. {
6. Set<Integer> data = new LinkedHashSet<Integer>();
7. data.add(31);
8. data.add(21);
9. data.add(41);
10. data.add(51);
11. data.add(11);
12. data.add(81);
13. System.out.println("Set: " + data);
14. System.out.println("Does the Set contains '91'?" + data.contains(91))
;
15. System.out.println("Does the Set contains 'javaTpoint'? "
+ data.contains("4"));
16. System.out.println("Does the Set contains '51'? " + data.contains(51)
);
17. }
18.}
Output:
5) containsAll()
ADVERTISEMENT
The method is used to check whether all the elements of the collection
are available in the existing set or not. It returns true if all the elements of
the collection are present in the set and returns false even if one of the
elements is missing in the existing set.
Syntax:
SetExample7.java
1. import java.io.*;
2. import java.util.*;
3. class containsAllMethod {
4. public static void main(String args[])
5. {
6. Set<Integer> data = new LinkedHashSet<Integer>();
7. data.add(31);
8. data.add(21);
9. data.add(41);
10. data.add(51);
11. data.add(11);
12. data.add(81);
13.
14. System.out.println("data: " + data);
15.
16. Set<Integer> newData = new LinkedHashSet<Integer>();
17. newData.add(31);
18. newData.add(21);
19. newData.add(41);
20.
21. System.out.println("\nDoes data contains newData?: "+ d
ata.containsAll(newData));
22.
23. }
24.}
Output:
6) hashCode()
The method is used to derive the hash code value for the current instance
of the set. It returns hash code value of integer type.
Syntax:
SetExample8.java
1. import java.io.*;
2. import java.util.*;
3. class hashCodeMethod {
4. public static void main(String args[])
5. {
6. Set<Integer> data = new LinkedHashSet<Integer>();
7. data.add(31);
8. data.add(21);
9. data.add(41);
10. data.add(51);
11. data.add(11);
12. data.add(81);
13. System.out.println("data: " + data);
14. System.out.println("\nThe hash code value of set is:"+ data.hashCode
());
15. }
16.}
Output:
7) isEmpty()
The isEmpty() method is used to identify the emptiness of the set . It
returns true if the set is empty and returns false if the set is not empty.
Syntax:
1. boolean isEmpty()
SetExample9.java
1. import java.io.*;
2. import java.util.*;
3. class isEmptyMethod {
4. public static void main(String args[])
5. {
6. Set<Integer> data = new LinkedHashSet<Integer>();
7. data.add(31);
8. data.add(21);
9. data.add(41);
10. data.add(51);
11. data.add(11);
12. data.add(81);
13. System.out.println("data: " + data);
14. System.out.println("\nIs data empty?: "+ data.isEmpty());
15. }
16.}
Output:
8) iterator()
The iterator() method is used to find the iterator of the set. The iterator is
used to get the element one by one.
ADVERTISEMENT
ADVERTISEMENT
Syntax:
SetExample10.java
1. import java.io.*;
2. import java.util.*;
3. class iteratorMethod {
4. public static void main(String args[])
5. {
6. Set<Integer> data = new LinkedHashSet<Integer>();
7. data.add(31);
8. data.add(21);
9. data.add(41);
10. data.add(51);
11. data.add(11);
12. data.add(81);
13. System.out.println("data: " + data);
14.
15. Iterator newData = data.iterator();
16. System.out.println("The NewData values are: ");
17. while (newData.hasNext()) {
18. System.out.println(newData.next());
19. }
20. }
21. }
Output:
9) remove()
The method is used to remove a specified element from the Set. Its return
value depends on the availability of the element. It returns true if the
element is available in the set and returns false if it is unavailable in the
set.
Syntax:
1. boolean remove(Object O)
SetExample11.java
1. import java.io.*;
2. import java.util.*;
3. class removeMethod {
4. public static void main(String args[])
5. {
6. Set<Integer> data = new LinkedHashSet<Integer>();
7. data.add(31);
8. data.add(21);
9. data.add(41);
10. data.add(51);
11. data.add(11);
12. data.add(81);
13. System.out.println("data: " + data);
14.
15. data.remove(81);
16. data.remove(21);
17. data.remove(11);
18. System.out.println("data after removing elements: " + data);
19. }
20.}
Output:
11) removeAll()
The method removes all the elements of the existing set from the
specified collection.
Syntax:
1. public boolean removeAll(Collection data)
SetExample12.java
1. import java.io.*;
2. import java.util.*;
3. class removeAllMethod {
4. public static void main(String args[])
5. {
6. Set<Integer> data = new LinkedHashSet<Integer>();
7. data.add(31);
8. data.add(21);
9. data.add(41);
10. data.add(91);
11. data.add(71);
12. data.add(81);
13. System.out.println("data: " + data);
14.
15. ArrayList<Integer> newData = new ArrayList<Integer>(
);
16. newData.add(91);
17. newData.add(71);
18. newData.add(81);
19. System.out.println("NewData: " + newData);
20.
21. data.removeAll(newData);
22. System.out.println("data after removing Newdata elements : " + data
);
23. }
24.}
Output:
11) retainAll()
The method retains all the elements from the set specified in the given
collection.
Syntax:
SetExample13.java
ADVERTISEMENT
1. import java.io.*;
2. import java.util.*;
3. class retainAllMethod {
4. public static void main(String args[])
5. {
6. Set<Integer> data = new LinkedHashSet<Integer>();
7. data.add(31);
8. data.add(21);
9. data.add(41);
10. data.add(91);
11. data.add(71);
12. data.add(81);
13. System.out.println("data: " + data);
14.
15. ArrayList<Integer> newData = new ArrayList<Integer>(
);
16. newData.add(91);
17. newData.add(71);
18. newData.add(81);
19. System.out.println("newData: " + newData);
20.
21. data.retainAll(newData);
22. System.out.println("data after retaining newdata elements : " + data)
;
23. }
24.}
Output:
12) size()
The method returns the size of the set.
Syntax:
1. int size()
SetExample14.java
1. import java.io.*;
2. import java.util.*;
3. class sizeMethod {
4. public static void main(String args[])
5. {
6. Set<Integer> data = new LinkedHashSet<Integer>();
7. data.add(31);
8. data.add(21);
9. data.add(41);
10. data.add(91);
11. data.add(71);
12. data.add(81);
13. System.out.println("data: " + data);
14.
15. System.out.println("size of the data is : " + data.size());
16. }
17. }
Output:
ADVERTISEMENT
13) removeAll()
The method is used to create an array with the same elements of the set.
Syntax:
1. Object[] toArray()
SetExample15.java
1. import java.io.*;
2. import java.util.*;
3. class toArrayMethod {
4. public static void main(String args[])
5. {
6. Set<Integer> data = new LinkedHashSet<Integer>();
7. data.add(31);
8. data.add(21);
9. data.add(41);
10. data.add(91);
11. data.add(71);
12. data.add(81);
13. System.out.println("data: " + data);
14.
15. Object[] array_data = data.toArray();
16. System.out.println("The array is:");
17. for (int i = 0; i < array_data.length; i++)
18. System.out.println(array_data[i]);
19. }
20.}
Output: