I want to combine the lists in stream.

Asked 1 years ago, Updated 1 years ago, 95 views

[[a, a, a], [b, b, b], [c, c]]

[a, a, a, b, b, b, c, c, c]
I'd like to do this, but is there any way I can do it on stream at once?

// This is what it looks like when you loop normally.
List innerA=Arrays.asList("a", "a", "a");
List innerB=Arrays.asList("b", "b", "b");
List innerC=Arrays.asList("c", "c", "c");
List<List>outer=Arrays.asList(innerA, innerB, innerC);
System.out.println(outer);
// [[a,a,a], [b,b,b], [c,c,c]]

List innerABC = new ArrayList<>();
for (List inner:outer) {
    innerABC.addAll(inner);
}
System.out.println (innerABC);
// [a, a, a, b, b, b, c, c, c]

java java8 stream

2022-09-30 11:01

2 Answers

You may be able to use Stream#flatMap(...).

import java.util.*;
import java.util.stream.*;
import java.util.function.*;

public class StreamTest{
  public static void main(String...args) {
    List<String> innerA=Arrays.asList("a", "a", "a");
    List<String> innerB=Arrays.asList("b", "b", "b");
    List<String> innerC=Arrays.asList("c", "c", "c");
    List<List<String>>outer=Arrays.asList(innerA,innerB,innerC);
    // List innerABC = new ArrayList<>();
    // for (List inner:outer) {
    //    innerABC.addAll(inner);
    //}
    List<String>innerABC=outer.stream()
      .flatMap(lst->lst.stream())
      .collect(Collectors.toList());

    System.out.println (innerABC);
  }
}


2022-09-30 11:01

It's a little strange, but how about this one?

Optional<List<String>>innerABC=outer.stream()
    .reduce(s1, s2)->concat(s1.stream(), s2.stream())
            .collect(Collectors.toList()));
if(innerABC.isPresent()){
   System.out.println(innerABC.get());
}


2022-09-30 11:01

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.