How to add selected items from a collection to an ArrayList in Java?
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]
My Personal Notes arrow_drop_up
Please Login to comment...