简体   繁体   English

如何使用Java Lambda创建/初始化ArrayList的ArrayList

[英]How to create/Initialize ArrayList of ArrayList using java Lambda

How to convert the following code to lambda in java8??? 如何在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++;
        }
    }

expected result: 预期结果:

[[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]] [[0,1,2,3,4,5,6,7,8,9],[10,11,12,13,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]]

You can use IntStream.range(int startInclusive, int endExclusive) to generate a stream of integers. 您可以使用IntStream.range(int startInclusive, int endExclusive)生成整数流。

You can then use mapToObj(IntFunction<? extends U> mapper) to process those integers. 然后,您可以使用mapToObj(IntFunction<? extends U> mapper)处理这些整数。

Finally, you can use collect(Collector<? super T,A,R> collector) to collect the values, eg to a List by using Collectors.toList() . 最后,您可以使用collect(Collector<? super T,A,R> collector)来收集值,例如,通过使用Collectors.toList()将其Collectors.toList()List

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());

UPDATE UPDATE

If you want to print the values as they are streamed, use peek(Consumer<? super T> action) . 如果要在流式传输值时打印它们,请使用peek(Consumer<? super T> action)

If the peek() method should see the value as an int , you can split the expression in the mapToObj so you can peek at the intermediate value, before it is converted to String . 如果peek()方法应该将该值视为一个int ,则可以在mapToObj拆分表达式,以便可以在将中间值转换为String之前对其进行窥视。

The conversion to String can then be done with a method reference, instead of a lambda. 然后,可以使用方法引用而不是lambda来转换为String

                 .mapToObj(i -> IntStream.range(0, 10)
                                         .map(j -> i * 10 + j)
                                         .peek(val -> System.out.println("Counter: " + val))
                                         .mapToObj(Integer::toString)
                                         .collect(Collectors.toList()))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM