2

How to convert the following code to lambda in java8???

    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]]

2
  • 2
    Lambda is (..) -> .. and it is implementation of functional interfaces. Did you mean streams which would give same result? BTW your current code doesn't compile, and while we could guess what it is supposed to it would be nice to have its logic and expected result in question itself. Commented Sep 23, 2018 at 20:25
  • @Pshemo edited and yes using streams Commented Sep 23, 2018 at 20:34

1 Answer 1

5

You can use IntStream.range(int startInclusive, int endExclusive) to generate a stream of integers.

You can then use mapToObj(IntFunction<? extends U> mapper) to process those integers.

Finally, you can use collect(Collector<? super T,A,R> collector) to collect the values, e.g. to a List by using 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());

UPDATE

If you want to print the values as they are streamed, use 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.

The conversion to String can then be done with a method reference, instead of a 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()))
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you!!This is great!! How to add counter to this code just like the example above?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.