如何将下面的代码转换为java8中的lambda???
List<List<String>> my2dList = new ArrayList<List<String>>();
int counter = 0;
for (int i = 0; i < 5; i++) {
my2dList.add(new ArrayList<String>());
for (int j = 0; j < 10; j++) {
System.out.println("Counter: " +counter);
my2dList.get(i).add(new String(""+counter));
counter++;
}
}
预期结果:
[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [10, 11, 12, 13, 14, 15, 16, 17, 18, 19], [20 , 21, 22, 23, 24, 25, 26, 27, 28, 29], [30, 31, 32, 33, 34, 35, 36, 37, 38, 39], [40, 41, 42, 43 , 44, 45, 46, 47, 48, 49]]
最佳答案
您可以使用 IntStream.range(int startInclusive, int endExclusive)
生成整数流。
然后您可以使用 mapToObj(IntFunction<? extends U> mapper)
处理这些整数。
最后,您可以使用 collect(Collector<? super T,A,R> collector)
收集值,例如到 List
通过使用 Collectors.toList()
.
List<List<String>> my2dList =
IntStream.range(0, 5)
.mapToObj(i -> IntStream.range(0, 10)
.mapToObj(j -> Integer.toString(i * 10 + j))
.collect(Collectors.toList()))
.collect(Collectors.toList());
更新
如果您想在流式传输时打印值,请使用 peek(Consumer<? super T> action)
.
如果peek()
方法应该将该值视为 int
,您可以拆分 mapToObj
中的表达式因此您可以在转换为 String
之前查看中间值.
转换为String
然后可以使用方法引用而不是 lambda 来完成。
.mapToObj(i -> IntStream.range(0, 10)
.map(j -> i * 10 + j)
.peek(val -> System.out.println("Counter: " + val))
.mapToObj(Integer::toString)
.collect(Collectors.toList()))
关于java - 如何使用 java Lambda 创建/初始化 ArrayList 的 ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52469923/