Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert List of List into list in java

Tags:

java

arraylist

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

like image 630
Manu Joy Avatar asked Apr 14 '15 18:04

Manu Joy


People also ask

How do I convert a list to another list in Java?

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.

How do I convert a list to one list in Java?

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.

How do you create an ArrayList from an existing list?

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.

Can we convert list to set in Java?

In this, we can convert the list items to set by using addAll() method. For this, we have to import the package java. util.


1 Answers

Try like this using flatMap:

List<List<Object>> list = 
List<Object> lst = list.stream()
        .flatMap(Collection::stream)
        .collect(Collectors.toList());
like image 60
Rahul Tripathi Avatar answered Oct 05 '22 04:10

Rahul Tripathi