Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java streams: Collect a nested collection

I'm learning how to use Java streams and need some help understanding how to stream nested collections and collect the results back into a collection.

In the simple example below, I've created 2 ArrayLists and added them to an ArrayList. I want to be able to perform a simple function on each nested collection and then capture the results into a new collection. The last line of code doesn't even compile. Any explanations would be appreciated!

    ArrayList<Integer> list1 = new ArrayList<Integer>(Arrays.asList(1,2,3));
    ArrayList<Integer> list2 = new ArrayList<Integer>(Arrays.asList(4,5,6));

    ArrayList<ArrayList<Integer>> nested = new ArrayList<ArrayList<Integer>>();
    nested.add(list1);
    nested.add(list2);

    ArrayList<ArrayList<Integer>> result = nested.stream()
            .map(list -> list.add(100))
            .collect(Collectors.toList());
like image 245
Steve Kim Avatar asked Nov 04 '17 17:11

Steve Kim


1 Answers

The problem is that List#add doesn't return a List. Instead, you need to return the list after the mapping:

List<ArrayList<Integer>> result = nested.stream()
        .map(list -> {
            list.add(100);
            return list;
        })
        .collect(Collectors.toList());

Or you may skip using map and do it using forEach, since ArrayList is mutable:

nested.forEach(list -> list.add(100));
like image 178
Luiggi Mendoza Avatar answered Oct 06 '22 01:10

Luiggi Mendoza