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]
- 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
- Garbage Collection in Java
- Iterator vs Collection in Java
- ArrayList in Java
- Arraylist.contains() in Java
- Java.util.Arraylist.indexOf() in Java
- Java.util.ArrayList.add() Method in Java
- Randomly select items from a List in Java
- Difference between Arrays and Collection in Java
- Convert an Iterable to Collection in Java
- Collection add() method in Java with Examples
- Collection contains() method in Java with Examples
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.