3

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?

0

2 Answers 2

9
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.

Sign up to request clarification or add additional context in comments.

Comments

0

in terms of speed and readability, I strongly recommend the previously mentioned solution from Avi

List<Integer> products = new ArrayList<>();
numbers.forEach( i -> numbers.forEach( j -> products.add( i * j ) ) ); 

Comments

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.