0% found this document useful (0 votes)
5 views57 pages

Collections in Java2

The document provides an overview of the Java Collections Framework, detailing its architecture for storing and manipulating groups of objects. It describes various interfaces such as Collection, List, and Iterator, along with their methods for adding, removing, and accessing elements. Additionally, it includes examples of using ArrayList and LinkedList, demonstrating how to iterate through collections and manipulate user-defined class objects.

Uploaded by

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

Collections in Java2

The document provides an overview of the Java Collections Framework, detailing its architecture for storing and manipulating groups of objects. It describes various interfaces such as Collection, List, and Iterator, along with their methods for adding, removing, and accessing elements. Additionally, it includes examples of using ArrayList and LinkedList, demonstrating how to iterate through collections and manipulate user-defined class objects.

Uploaded by

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

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.

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.
Methods of Collection interface

There are many methods declared in the Collection interface. They are as follows:

No Method Description
.

1 public boolean add(E e) It is used to insert an element in this collection.

2 public boolean addAll(Collection<? It is used to insert the specified collection elements in


extends E> c) the invoking collection.

3 public boolean remove(Object It is used to delete an element from the collection.


element)

4 public boolean It is used to delete all the elements of the specified


removeAll(Collection<?> c) collection from the invoking collection.

5 public boolean retainAll(Collection<?> It is used to delete all the elements of invoking


c) collection except the specified collection.

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.

8 public boolean contains(Object It is used to search an element.


element)

9 public boolean It is used to search the specified collection in the


containsAll(Collection<?> c) collection.

10 public Iterator iterator() It returns an iterator.

11 public Object[] toArray() It converts collection into array.

12 public boolean isEmpty() It checks if collection is empty.

13 public boolean equals(Object element) It matches two collections.


19 public int hashCode() It returns the hash code number of the collection.

// Java code to illustrate adding


// elements to the Collection

import java.io.*;
import java.util.*;

public class AddingElementsExample {


public static void main(String[] args)
{

// create an empty array list with an initial


// capacity
Collection<Integer> list1 = new ArrayList<Integer>(5);

// use add() method to add elements in the list


list1.add(15);
list1.add(20);
list1.add(25);

// prints all the elements available in list


for (Integer number : list1) {
System.out.println("Number = " + number);
}

// Creating an empty ArrayList


Collection<Integer> list2 = new ArrayList<Integer>();
// Appending the collection to the list
list2.addAll(list1);

// displaying the modified ArrayList


System.out.println("The new ArrayList is: " + list2);
}
}

Iterator interface
Iterator interface provides the facility of iterating the elements in a forward direction only.

Methods of Iterator interface

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.

It contains only one abstract method. i.e.,

1. Iterator<T> iterator()

It returns the iterator over the elements of type T.


Collection Interface

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.

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.

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++.

Java ArrayList Example

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:

[Mango, Apple, Banana, Grapes]


Iterating ArrayList using Iterator

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:

Returning element: Apple


Mango
Dates
Banana
Grapes
How to Sort ArrayList

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

There are various ways to traverse the collection elements:

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.

Iterating Collection through remaining ways

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:

Traversing list through List Iterator:


Ajay
Ravi
Vijay
Ravi
Traversing list through for loop:
Ravi
Vijay
Ravi
Ajay
Traversing list through forEach() method:
Ravi
Vijay
Ravi
Ajay
Traversing list through forEachRemaining() method:
Ravi
Vijay
Ravi
Ajay

User-defined class objects in Java ArrayList

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.

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.

Doubly Linked List

In the case of a doubly linked list, we can add or remove elements from both sides.

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 add elements

Here, we see different ways to add elements.

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]

Java LinkedList example to remove elements

Here, we see different ways to remove an element.

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: []

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

Java LinkedList Example: Book


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 LinkedListExample {
15. public static void main(String[] args) {
16. //Creating list of Books
17. List<Book> list=new LinkedList<Book>();
18. //Creating Books
19. Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
20. Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc
Graw Hill",4);
21. Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
22. //Adding Books to list
23. list.add(b1);
24. list.add(b2);
25. list.add(b3);
26. //Traversing list
27. for(Book b:list){
28. System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);
29. }
30. }
31. }

Output:

101 Let us C Yashwant Kanetkar BPB 8


102 Data Communications & Networking Forouzan Mc Graw Hill 4
103 Operating System Galvin Wiley 6
Java Vector

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:

Elements are: [Tiger, Lion, Dog, Elephant, Rat, Cat, Deer]


Java Vector Example 2
1. import java.util.*;
2. public class VectorExample1 {
3. public static void main(String args[]) {
4. //Create an empty vector with initial capacity 4
5. Vector<String> vec = new Vector<String>(4);
6. //Adding elements to a vector
7. vec.add("Tiger");
8. vec.add("Lion");
9. vec.add("Dog");
10. vec.add("Elephant");
11. //Check size and capacity
12. System.out.println("Size is: "+vec.size());
13. System.out.println("Default capacity is: "+vec.capacity());
14. //Display Vector elements
15. System.out.println("Vector element is: "+vec);
16. vec.addElement("Rat");
17. vec.addElement("Cat");
18. vec.addElement("Deer");
19. //Again check size and capacity after two insertions
20. System.out.println("Size after addition: "+vec.size());
21. System.out.println("Capacity after addition is: "+vec.capacity());
22. //Display Vector elements again
23. System.out.println("Elements are: "+vec);
24. //Checking if Tiger is present or not in this vector
25. if(vec.contains("Tiger"))
26. {
27. System.out.println("Tiger is present at the index " +vec.indexOf("Tiger"));
28. }
29. else
30. {
31. System.out.println("Tiger is not present in the list.");
32. }
33. //Get the first element
34. System.out.println("The first animal of the vector is = "+vec.firstElement());
35. //Get the last element
36. System.out.println("The last animal of the vector is = "+vec.lastElement());
37. }
38. }
Test it Now

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

Java Stack Class

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.

Stack Class Constructor

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.

1. Stack stk = new Stack();

Or

1. Stack<type> stk = new Stack<>();

Where type denotes the type of stack like Integer, String, etc.

Methods of the Stack Class

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.

Method Modifier and Method Description


Type

empty() boolean The method checks the stack is empty or not.

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.

Stack Class empty() Method

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

1. public boolean empty()


Returns: The method returns true if the stack is empty, else returns false.

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:

Is the stack empty? true


Elements in Stack: [78, 113, 90, 120]
Is the stack empty? false
Stack Class push() Method

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

1. public E push(E item)

Parameter: An item to be pushed onto the top of the stack.

Returns: The method returns the argument that we have passed as a parameter.

Stack Class pop() Method

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()

Returns: It returns an object that is at the top of the stack.

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()

Returns: It returns the top elements of the stack.

Let's see an example of the peek() method.

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:

Stack: [Apple, Grapes, Mango, Orange]


Element at the top of the stack: Orange
Stack Class search() Method

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

1. public int search(Object o)

Parameter: o is the desired object to be searched.

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.

Let's see an example of the search() method.

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

1. public int size()

Let's see an example of the size() method of the Vector class.

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. }

Queue Interface In Java





The Queue interface is present in java.util package and extends the Collection interface is
used to hold the elements about to be processed in FIFO(First In First Out) order. It is an
ordered list of objects with its use limited to inserting elements at the end of the list and
deleting elements from the start of the list, (i.e.), it follows the FIFO or the First-In-First-Out
principle.

Example:

 Java
import java.util.LinkedList;
import java.util.Queue;

public class QueueExample {


public static void main(String[] args) {
Queue<String> queue = new LinkedList<>();

// add elements to the queue


queue.add("apple");
queue.add("banana");
queue.add("cherry");

// print the queue


System.out.println("Queue: " + queue);

// remove the element at the front of the queue


String front = queue.remove();
System.out.println("Removed element: " + front);

// print the updated queue


System.out.println("Queue after removal: " + queue);

// add another element to the queue


queue.add("date");

// peek at the element at the front of the queue


String peeked = queue.peek();
System.out.println("Peeked element: " + peeked);

// print the updated queue


System.out.println("Queue after peek: " + 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

// Java program to demonstrate a Queue

import java.util.LinkedList;
import java.util.Queue;

public class QueueExample {

public static void main(String[] args)


{
Queue<Integer> q
= new LinkedList<>();

// Adds elements {0, 1, 2, 3, 4} to


// the queue
for (int i = 0; i < 5; i++)
q.add(i);
// Display contents of the queue.
System.out.println("Elements of queue "
+ q);

// To remove the head of queue.


int removedele = q.remove();
System.out.println("removed element-"
+ removedele);

System.out.println(q);

// To view the head of queue


int head = q.peek();
System.out.println("head of queue-"
+ head);

// Rest all methods of collection


// interface like size and contains
// can be used with this
// implementation.
int size = q.size();
System.out.println("Size of queue-"
+ size);
}
}

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

// Java program to add elements


// to a Queue

import java.util.*;

public class GFG {

public static void main(String args[])


{
Queue<String> pq = new PriorityQueue<>();

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

// Java program to remove elements


// from a Queue

import java.util.*;

public class GFG {

public static void main(String args[])


{
Queue<String> pq = new PriorityQueue<>();

pq.add("Geeks");
pq.add("For");
pq.add("Geeks");

System.out.println("Initial Queue " + pq);

pq.remove("Geeks");

System.out.println("After Remove " + pq);

System.out.println("Poll Method " + pq.poll());

System.out.println("Final Queue " + pq);


}
}
Output
Initial Queue [For, Geeks, Geeks]
After Remove [For, Geeks]
Poll Method For
Final Queue [Geeks]
3. Iterating the Queue: There are multiple ways to iterate through the Queue. The most
famous way is converting the queue to the array and traversing using the for loop.
However, the queue also has an inbuilt iterator which can be used to iterate through the
queue.
Example
 Java

// Java program to iterate elements


// to a Queue

import java.util.*;

public class GFG {

public static void main(String args[])


{
Queue<String> pq = new PriorityQueue<>();

pq.add("Geeks");
pq.add("For");
pq.add("Geeks");

Iterator iterator = pq.iterator();

while (iterator.hasNext()) {
System.out.print(iterator.next() + " ");
}
}
}

Java Deque Interface


The interface called Deque is present in java.util package. It is the subtype of the interface
queue. The Deque supports the addition as well as the removal of elements from both ends of
the data structure. Therefore, a deque can be used as a stack or a queue. We know that the
stack supports the Last In First Out (LIFO) operation, and the operation First In First Out is
supported by a queue. As a deque supports both, either of the mentioned operations can be
performed on it. Deque is an acronym for "double ended queue".

Java ArrayDeque Example

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:

After offerFirst Traversal...


jai
arvind
vimal
mukul
After pollLast() Traversal...
jai
arvind
vimal
Java ArrayDeque Example: Book

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:

101 Let us C Yashwant Kanetkar BPB 8


102 Data Communications & Networking Forouzan Mc Graw Hill 4
103 Operating System Galvin Wiley 6
Set in Java
The set is an interface available in the java.util package.
The set interface extends the Collection interface. An unordered
collection or list in which duplicates are not allowed is referred to as
a collection interface. The set interface is used to create the
mathematical set. The set interface use collection interface's methods to
avoid the insertion of the same elements

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.

Operations on the Set Interface


On the Set, we can perform all the basic mathematical operations like
intersection, union and difference.

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:

o Intersection: The intersection operation returns all those elements which


are present in both the set. The intersection of set1 and set2 will be [33,
45, 55].
o Union: The union operation returns all the elements of set1 and set2 in a
single set, and that set can either be set1 or set2. The union of set1 and
set2 will be [2, 3, 12, 22, 33, 34, 45, 55, 66, 77, 83].
o Difference: The difference operation deletes the values from the set
which are present in another set. The difference of the set1 and set2 will
be [66, 34, 22, 77].

In set, addAll() method is used to perform the union, retainAll() method


is used to perform the intersection and removeAll() method is used to
perform difference. Let's take an example to understand how these
methods are used to perform the intersection, union, and difference
operations.

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.

For performing the intersection, we create a new


set intersection_data with the same element of the set1. We then call
the retainAll() method of set and pass the set2 as an argument to it. This
method will get all those elements from the intersection_data which are
present in set2 and store it in the intersection_data. Now, the
intersection_data contains the intersect value of both the sets.

For performing the difference, we create a new set difference_data with


the same element of the set1. We then call the removeAll() method of set
and pass the set2 as an argument to it. This method will remove all those
elements from the difference_data which are present in the set2 and
gives the difference of both the 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:

1. boolean add(type element).

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:

1. boolean addAll(Collection data)

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:

1. void clear() SetExample5.java


1. import java.io.*;
2. import java.util.*;
3. public class clearMethod {
4. public static void main(String args[])
5. {
6. Set<Integer> data = new LinkedHashSet<Integer>();
7.
8. data.add(31);
9. data.add(21);
10. data.add(41);
11. System.out.println("Set: " + data);
12.
13. data.clear();
14. System.out.println("The final set: " + data);
15. }
16.}

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:

1. boolean contains(Object element)

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:

1. public boolean containsAll(Collection data)

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:

1. public int hashCode()

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:

1. Iterator iterate_value = set1.iterator();

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:

1. public boolean retainAll(Collection data)

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:

You might also like