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?

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
puhlerblet
  • 113
  • 5

2 Answers2

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.

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
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 ) ) ); 
Kaplan
  • 2,572
  • 13
  • 14