Given a Collection with some values, the task is to add selected the items of this Collection to an ArrayList in Java.
Input: Collection = [1, 2, 3], condition = (item != 2)
Output: ArrayList = [1, 3]
Input: Collection = [GFG, Geek, GeeksForGeeks], condition = (item != GFG)
Output: ArrayList = [Geek, GeeksForGeeks]
- Get the Collection whose selected items are to be added into the ArrayList
- Create an ArrayList
- Add selected items of Collection into this ArrayList using Stream
- Generate the stream with all the items of the collection using stream() method
- Select the required items from the Stream using filter() method
- Collect the selected items of the stream as an ArrayList using forEachOrdered() method
- ArrayList with selected items of Collections have been created.
Below is the implementation of the above approach:
ArrayList with selected elements of collection [1, 2, 3]: [1, 3]
ArrayList with selected elements of collection [GFG, Geeks, GeeksForGeeks]: [Geeks, GeeksForGeeks]
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- How to add all items from a collection to an ArrayList in Java?
- Java Collection| Difference between Synchronized ArrayList and CopyOnWriteArrayList
- ArrayList of ArrayList in Java
- Java.util.ArrayList.addall() method in Java
- Java.util.ArrayList.add() Method in Java
- Java.util.Arraylist.indexOf() in Java
- Arraylist.contains() in Java
- ArrayList in Java
- Iterator vs Collection in Java
- Garbage Collection in Java
- Synchronization of ArrayList in Java
- Initialize an ArrayList in Java
- Reverse an ArrayList in Java
- Vector vs ArrayList in Java
- Array of ArrayList in Java
- ArrayList trimToSize() in Java with example
- ArrayList isEmpty() in Java with example
- ArrayList vs. HashMap in Java
- ArrayList vs LinkedList in Java
- Arraylist lastIndexOf() in Java with example
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.