2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Java 8 で ruby の flatten

Last updated at Posted at 2015-06-01

ruby には flatten という配列のメソッドがあります。

arr = [1, 2, 3, [4, 5], [6, [7, 8]]]
p arr.flatten

これを Java 8 でやろうとすると多分これが一番楽だと思います。

int[][] list = {{1, 2, 3}, {4}, {5, 6}};
int[] a = Arrays.stream(list).flatMapToInt(Arrays::stream).toArray();

List だとこんな感じ

List<List<Integer>> list = Arrays.asList(
        Arrays.asList(1, 2, 3),
        Arrays.asList(4),
        Arrays.asList(5, 6)
);
List<Integer> flatten = list.stream().flatMap(Collection::stream).collect(Collectors.toList());

これが一番楽だよ……ね……?

さっそく追記:このコード、2次元配列限定でしか動かないですね。引用してるrubyの例を再現できてない。。めんどうなんでこれ以上掘り下げないですが、3次元でもいけそうではあるかな。

2
2
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?