20. boolean retainAll(Collection c)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
 
<strong>20. boolean	retainAll(Collection<?> c)</strong>
Retains only the elements in this list that are contained in the specified collection.
package com.spy.arraylist.method;
 
import java.util.ArrayList;
 
public class RetainAll 
{
 
	public static void main(String[] args) 
 
	{
 
		 ArrayList<String> emp_list=new ArrayList<>();
 
			emp_list.add("Bhavesh Lakhani");
			emp_list.add("Abhilash Shah");
			emp_list.add("Nilay Shah");
			emp_list.add("Vaibhav Prajapati");
 
 
			System.out.println("List 1 Element");
			System.out.println("***************");
 
			for (String s : emp_list) 
			{
			  System.out.println(s);
			}
 
			ArrayList<String> emp_list2=new ArrayList<>();
 
			emp_list2.add("Bhavesh Lakhani");
			emp_list2.add("Nilay Shah");
 
			System.out.println("List 2 element");
			System.out.println("***************");
 
			for (String s : emp_list2)
			{
			System.out.println(s);	
			}
 
 
			 //Removing element from emp_list1 which is present in emp_list2
			 emp_list.retainAll(emp_list2);
 
			System.out.println("Now in emp_list1 contain only emp_list2");
 
			for (String s : emp_list) 
			{
				System.out.println(s);
			}	
 
 
 
	}
 
}

Output:

1
2
3
4
5
6
7
8
9
10
11
12
13
List 1 Element
***************
Bhavesh Lakhani
Abhilash Shah
Nilay Shah
Vaibhav Prajapati
List 2 element
***************
Bhavesh Lakhani
Nilay Shah
Now in emp_list1 contain only emp_list2
Bhavesh Lakhani
Nilay Shah

Leave a Reply

Your email address will not be published. Required fields are marked *