

[[a, a, a], [b, b, b], [c, c, c]]  
を  
[a,a,a,b,b,b,c,c,c]  
こうしたいのですが、streamで一発で出来る方法ってありますか？

[code]

    //普通にループするとこんな感じです。
    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]
    
[/code]


CC BY-SA 3.0
2015-03-22T08:28:39.883
8232
2015-03-25T13:55:52.137
2015-03-23T05:37:32.030
46
8949
question
java java8 stream
streamでリストの結合がしたい


[Stream#flatMap(...)](http://docs.oracle.com/javase/jp/8/docs/api/java/util/stream/Stream.html#flatMap-
java.util.function.Function-)が使えるかもしれません。

[code]

    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);
      }
    }
    
[/code]


CC BY-SA 3.0
2015-03-22T17:13:25.780
8238
2015-03-22T17:13:25.780
46
8232
answer


ちょっと変わった方法ですがこんなのもどうですか？

[code]

    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());
    }
    
[/code]


CC BY-SA 3.0
2015-03-25T06:04:15.687
8366
2015-03-25T13:55:52.137
2015-03-25T13:55:52.137
49
2869
8232
answer