Reputation: 123
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?
Upvotes: 3
Views: 207
Reputation: 3728
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 ) ) );
Upvotes: 0
Reputation: 49606
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.
Upvotes: 9