Java streams: Collect a nested collection

Steve Kim :

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());
Luiggi Mendoza :

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));

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=462666&siteId=1