List<List<String>> superlist = new ArrayList<List<String>>();
List<String> list1 = new ArrayList<String>();
list1.add("a1");
list1.add("a2");
List<String> list2 = new ArrayList<String>();
list2.add("b1");
list2.add("b2");
List<String> list3= new ArrayList<String>();
list3.add("c1");
list3.add("c2");
superlist.add(list1);
superlist.add(list2);
superlist.add(list3);
List<String> result= new ArrayList<>();
Now I want to create a new list which contains all the values in superList
.
Here result should contain a1,a2,b1,b2,c1,c2
Another approach to copying elements is using the addAll method: List<Integer> copy = new ArrayList<>(); copy. addAll(list); It's important to keep in mind whenever using this method that, as with the constructor, the contents of both lists will reference the same objects.
The standard solution is to use the Stream. flatMap() method to flatten a List of Lists. The flatMap() method applies the specified mapping function to each element of the stream and flattens it.
Using a Copy Constructor: Using the ArrayList constructor in Java, a new list can be initialized with the elements from another collection. Syntax: ArrayList cloned = new ArrayList(collection c); where c is the collection containing elements to be added to this list.
In this, we can convert the list items to set by using addAll() method. For this, we have to import the package java. util.
Try like this using flatMap
:
List<List<Object>> list =
List<Object> lst = list.stream()
.flatMap(Collection::stream)
.collect(Collectors.toList());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With