Use stream() to convert nested list into list

I have an arraylist ‘response’ with each element containing an object Meta and List(Values) i.e. a list which contains nested list and some meta data for each nested list. I would like to use stream() on this to create a new list. The new list will contain all the value objects and its corresponding meta data. How can i use response.stream() to accomplish this?

    //Input
    Meta meta1 = new Meta("name1");
    Meta meta2 = new Meta("name2");
    Meta meta3 = new Meta("name3");
    List<Values> values1 = new ArrayList<>();
    values1.add(new Values("1 Aug", 1.0F));
    values1.add(new Values("2 Aug", 2.0F));
    values1.add(new Values("3 Aug", 3.0F));
    List<Values> values2 = new ArrayList<>();
    values2.add(new Values("1 Aug", 4.0F));
    values2.add(new Values("2 Aug", 5.0F));
    values2.add(new Values("3 Aug", 6.0F));
    List<Values> values3 = new ArrayList<>();
    values3.add(new Values("1 Aug", 7.0F));
    values3.add(new Values("2 Aug", 8.0F));
    values3.add(new Values("3 Aug", 9.0F));
    Response response1 = new Response(meta1, values1);
    Response response2 = new Response(meta2, values2);
    Response response3 = new Response(meta3, values3);
    List<Response> response = new ArrayList<>();
    response.add(response1);
    response.add(response2);
    response.add(response3);

    //use response.stream()...

    //output
    List<MetaValue> metaValueList = new ArrayList<>();
    metaValueList.add(new MetaValue("name1", "1 Aug", 1.0F));
    metaValueList.add(new MetaValue("name1", "2 Aug", 2.0F));
    metaValueList.add(new MetaValue("name1", "3 Aug", 3.0F));
    metaValueList.add(new MetaValue("name2", "1 Aug", 4.0F));
    metaValueList.add(new MetaValue("name2", "2 Aug", 5.0F));
    metaValueList.add(new MetaValue("name2", "3 Aug", 6.0F));
    metaValueList.add(new MetaValue("name3", "1 Aug", 7.0F));
    metaValueList.add(new MetaValue("name3", "2 Aug", 8.0F));
    metaValueList.add(new MetaValue("name3", "3 Aug", 9.0F));

Answer

You need to stream the responses and flatMap the values. I’ll take some liberty with the naming because you haven’t provided class definitions, but this should give you an idea:

List<MetaValue> metaValueList = response.stream()
        .flatMap(r -> r.getValues()
                .stream()
                .map(v -> new MetaValue(r.getMeta().getName(), v.getDate(), v.getValue())))
        .collect(Collectors.toList());