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.
Examples:
Input: Collection = [1, 2, 3], condition = (item != 2)
Output: ArrayList = [1, 3]Input: Collection = [GFG, Geek, GeeksForGeeks], condition = (item != GFG)
Output: ArrayList = [Geek, GeeksForGeeks]
Approach:
- 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:
// Java program to add selected items // from a collection to an ArrayList import java.io.*; import java.util.*; import java.util.stream.*; class GFG { // Function to add selected items // from a collection to an ArrayList public static <T> ArrayList<T> createArrayList(List<T> collection, T N) { // Create an ArrayList ArrayList<T> list = new ArrayList<T>(); // Add selected items of Collection // into this ArrayList // Here select items if // they are not equal to N collection.stream() .filter(item -> !item.equals(N)) .forEachOrdered(list::add); return list; } // Driver code public static void main(String[] args) { List<Integer> collection1 = Arrays.asList( 1 , 2 , 3 ); System.out.println( "ArrayList with selected " + "elements of collection " + collection1 + ": " + createArrayList(collection1, 2 )); List<String> collection2 = Arrays.asList( "GFG" , "Geeks" , "GeeksForGeeks" ); System.out.println( "ArrayList with selected " + "elements of collection " + collection2 + ": " + createArrayList(collection2, "GFG" )); } } |
Output:
ArrayList with selected elements of collection [1, 2, 3]: [1, 3]
ArrayList with selected elements of collection [GFG, Geeks, GeeksForGeeks]: [Geeks, GeeksForGeeks]
Please Login to comment...