Manu Joy
Manu Joy

Reputation: 1769

Convert List of List into list in java

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

Upvotes: 25

Views: 40355

Answers (5)

nagendra babu
nagendra babu

Reputation: 57

This works for me!

List<String> result= new ArrayList<>();
    
    superlist.stream().forEach(
            
            n->result.addAll(n)
            );
    
    System.out.println(result);

Upvotes: 0

Rahul Tripathi
Rahul Tripathi

Reputation: 172438

Try like this using flatMap:

List<List<Object>> list = 
List<Object> lst = list.stream()
        .flatMap(Collection::stream)
        .collect(Collectors.toList());

Upvotes: 60

Mick Mnemonic
Mick Mnemonic

Reputation: 7956

If you're on Java < 8 (and cannot use Streams), you can do this in a one-liner with Guava's Iterables.concat:

List<String> merged = Lists.newArrayList(Iterables.concat(superList));

Upvotes: 7

Manu Joy
Manu Joy

Reputation: 1769

superlist.forEach(e -> result.addAll(e));

Now after some reasarch, I found this way.

Upvotes: 3

camelsaucerer
camelsaucerer

Reputation: 301

You would have to loop through every List in your superlist object in order to get all of the contents. You can use the addAll() method to copy each list's contents to your new List:

List<String> result = new ArrayList<String>();
for (List<String> list : superlist) {
    result.addAll(list);
}

Upvotes: 2

Related Questions