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 Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.