如何使用Stream填充矩阵?

huangapple go评论60阅读模式
英文:

How to fill matrix using Stream?

问题

我想学习一些Java中的函数式编程和流操作,这里是我想要接收的矩阵:

Integer[][] availableValues = new Integer[][]{{1,2,3},{1,2,3},{1,2,3},{1,2,3}};

是否有办法使用流来填充这个矩阵,但使用给定的值?(伪代码)

for (数组 在 矩阵中) 
  for (值 在 数组中) 
    for (在范围(1,4)之间的下一个值)
= 介于1和4之间的下一个值

是否有办法在矩阵中的每个数组中使用流将值从1填充到X?
类似于 Arrays.stream(availableValues).map(x -> IntStream.range(1, 10).forEach(i -> x = i)); 但这显然行不通。

英文:

I want to learn some functional programing and streams in Java, here is the matrix that I want to receive:

Integer[][] availableValues = new Integer[][]{{1,2,3},{1,2,3},{1,2,3},{1,2,3}};

Is there any way to fill this matrix with given values but using Streams? (pseudo code)

for array in matrix
  for value in array
    for range(1,4)
      value = next value between 1 and 4

Is there any way to put values from 1 to X in every array in matrix using Streams?
Something like Arrays.stream(availableValues).map(x->IntStream.range(1,10).forEach(i -> x = i)); but it's obviously not working.

答案1

得分: 2

尝试这个:

  • 你想要创建4个大小为3的数组的数组,每个数组包含1、2、3。
  • 映射的内部流创建其中一个数组。
  • 外部流执行这个操作4次,并创建一个包含这些数组的数组。
int[][] v = IntStream.range(1, 5)
        .mapToObj(a -> IntStream.range(1, 4).toArray())
		.toArray(int[][]::new);

for (int[] arr : v) {
	System.out.println(Arrays.toString(arr));
}

输出结果:

[1, 2, 3]
[1, 2, 3]
[1, 2, 3]
[1, 2, 3]
英文:

Try this:

  • You want to create 4 arrays of arrays of size 3 that each contain 1,2,3.
  • the mapped inner stream creates one of those arrays.
  • the outer stream does that 4 times and creates an array of those arrays.
int[][] v = IntStream.range(1, 5)
        .mapToObj(a -> IntStream.range(1, 4).toArray())
		.toArray(int[][]::new);

for (int[] arr : v) {
	System.out.println(Arrays.toString(arr));
}

Prints

[1, 2, 3]
[1, 2, 3]
[1, 2, 3]
[1, 2, 3]

</details>



# 答案2
**得分**: 0

这应该是这样的:
```java
int[][] arr = IntStream.range(0, 4)
                       .mapToObj(i -> IntStream.range(1, 4).toArray())
                       .collect(Collectors.toList()).toArray(int[][]::new);
Arrays.stream(arr).forEach(a -> System.out.println(Arrays.toString(a)));

输出:

[1, 2, 3]
[1, 2, 3]
[1, 2, 3]
[1, 2, 3]
英文:

It should be like this:

int[][] arr = IntStream.range(0, 4)
                       .mapToObj(i -&gt; IntStream.range(1, 4).toArray())
                       .collect(Collectors.toList()).toArray(int[][]::new);
Arrays.stream(arr).forEach(a -&gt; System.out.println(Arrays.toString(a)));

output

[1, 2, 3]
[1, 2, 3]
[1, 2, 3]
[1, 2, 3]

huangapple
  • 本文由 发表于 2020年10月9日 05:48:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/64271109.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定