我正在尝试从n维int
数组中获取IntStream
。有没有一种很好的API方法可以做到这一点?我知道两个流的连接方法。
发布于 2014-03-24 13:08:35
假设您想要在行-主方法中按顺序处理数组的数组,这应该是可行的:
int[][] arr = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
IntStream stream = Arrays.stream(arr).flatMapToInt(x -> Arrays.stream(x));
首先,它调用Arrays.stream(T[])
方法(其中T
被推断为int[]
)来获取Stream<int[]>
,然后Stream#flatMapToInt()
方法使用Arrays.stream(int[])
方法将每个int[]
元素映射到IntStream
。
发布于 2017-07-13 22:18:41
为了进一步扩展Rohit的答案,可以使用方法引用来略微缩短所需的代码量:
int[][] arr = { {1, 2, 3},
{4, 5, 6},
{7, 8, 9} };
IntStream stream = Arrays.stream(arr).flatMapToInt(Arrays::stream);
发布于 2018-11-13 04:21:58
要只处理这些元素,可以像Rohit的答案中那样使用flatMap
。
要处理带有索引的元素,您可以使用IntStream.range
,如下所示。
import java.util.stream.IntStream;
import static java.util.stream.IntStream.range;
public class StackOverflowTest {
public static void main(String... args) {
int[][] arr = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
// Map the two dimensional array with indices.
final IntStream intStream = range(0, arr.length).flatMap(row -> range(0, arr[row].length).map(col -> {
final int element = arr[row][col];
// E.g. multiply elements in odd numbered rows and columns by two.
return row % 2 == 1 || col % 2 == 1 ? element * 2 : element;
}));
// Prints "1 4 3 8 10 12 7 16 9 ".
intStream.forEachOrdered(n -> System.out.print(n + " "));
}
}
https://stackoverflow.com/questions/22601036
复制相似问题