将IntStream转换为二维数组

时间:2018-01-19 08:52:18

标签: java java-stream

我将int [][]展平为IntStream后。我需要将它拆分回来#34;按照这个算法进入小二维数组:

IntSream [1,2,3,4] -> int [][] finalArr {{1,2},{2,3},{3,4}}

基本上,将两个最近的元素组合成数组。我觉得有可能再次使用flatMap,但我无法弄明白。有什么建议吗?

1 个答案:

答案 0 :(得分:1)

您可以从<object typemustmatch type="image/svg+xml" data="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4NCjxzdmcgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB3aWR0aD0iMTIwIiBoZWlnaHQ9IjQwIj4NCiAgPHN3aXRjaD4NCiAgICA8Zm9yZWlnbk9iamVjdCByZXF1aXJlZEV4dGVuc2lvbnM9Imh0dHA6Ly93d3cudzMub3JnLzE5OTgvTWF0aC9NYXRoTUwiIHdpZHRoPSIxMjAiIGhlaWdodD0iNDAiPg0KICAgICAgPG1hdGggeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzE5OTgvTWF0aC9NYXRoTUwiPg0KICAgICAgICA8bW4+MTwvbW4+PG1vPis8L21vPjxtbj4xPC9tbj48bW8+PTwvbW8+PG1uPjI8L21uPjxtdGV4dD5NYXRoTUw8L210ZXh0Pg0KICAgICAgPC9tYXRoPg0KICAgIDwvZm9yZWlnbk9iamVjdD4NCiAgICA8dGV4dCB5PSIxNSIgZm9udC1zaXplPSIxNiI+MSArIDEgPSAyIChTVkcpPC90ZXh0Pg0KICA8L3N3aXRjaD4NCjwvc3ZnPg=="> 1 + 1 = 2 (You don't support SVG) </object>获取List(list)并使用以下代码创建两对的2D数组:

IntStream

打印输出:

import java.util.Arrays;
import java.util.List;
import  java.util.stream.IntStream;

public class Stream1 {
    public static void main(String[] args) {
        List<Integer> list = Arrays.asList(1, 2, 3,4);

        int [][] int2DArray = IntStream.range(1, list.size())
                .mapToObj(i -> new int[] {list.get(i-1), list.get(i)})
                .toArray(int[][]:: new);

        System.out.println(Arrays.deepToString(int2DArray));
    }
}