- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to retain elements from a Collection in another Collection
Let’s say the following is our Collection i.e. ArrayList −
List<Integer>list = new ArrayList<Integer>(); list.add(100); list.add(200); list.add(200); list.add(200); list.add(300); list.add(400); list.add(400); list.add(500);
Now, create another Collection −
List <Integer> list2 = new ArrayList<Integer>(); list2.add(100); list2.add(200); list2.add(300); list2.add(400);
To retain all elements from a Collection in another Collection, try the following with list and list2 as our two Collections −
list.retainAll(list2);
Example
import java.util.ArrayList; import java.util.List; public class Demo { public static void main(String args[]) throws Exception { List<Integer>list = new ArrayList<Integer>(); list.add(100); list.add(200); list.add(200); list.add(200); list.add(300); list.add(400); list.add(400); list.add(500); List <Integer>list2 = new ArrayList<Integer>(); list2.add(100); list2.add(200); list2.add(300); list2.add(400); list.retainAll(list2); System.out.println("Resultant list = "+list); } }
Output
Resultant list = [100, 200, 200, 200, 300, 400, 400]
- Related Articles
- How to remove all elements from a Collection in another Collection
- Create a Queue from another collection in C#?
- Append all elements of another Collection to a Vector in Java
- How to copy a collection from one database to another in MongoDB?
- Create HashSet from another collection in C#
- Retrieving Elements from Collection in C#
- Check if a Java HashSet Collection contains another Collection
- Create a new ArrayList from another collection in Java
- Create Octet Tuple from another collection in Java
- Create Ennead Tuple from another collection in Java
- Create Decade Tuple from another collection in Java
- Create LabelValue Tuple from another collection in Java
- Create KeyValue Tuple from another collection in Java
- Create Pair Tuple from another collection in Java
- Create Quintet Tuple from another collection in Java

Advertisements