Using streams instead of nested for loops

puhlerblet :

I'm currently learning java 8 streams. I have a list of integers, with values from 1 to 1000. Now, I want to create a new list of integers, where each element is the result of multiplying each element of the numbers list with each other element of the numbers list.

The following code does the job:

        List<Integer> numbers = IntStream
                .range(1,999)
                .mapToObj(Integer::valueOf)
                .collect(Collectors.toList());

        List<Integer> products = new ArrayList<>();
        for (Integer i : numbers) {
            for (Integer j : numbers) {
                products.add(i*j);
            }
        }

I would like to know if there's a way to avoid the nested for loop by using streams?

Andrew Tobilko :
List<Integer> products = numbers.stream()
        .flatMap(i -> numbers.stream().map(j -> i * j))
        .collect(Collectors.toList());

i -> numbers.stream().map(j -> i * j) is a Function to get a Stream of products for a particular i. Use it to generate a Stream<Integer> for each element in numbers, flatMap that s***, and collect the result into a List.

I wouldn't say it looks/performs better than the plain version you've come up with.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=306028&siteId=1