I have a scenario in which I have two loops, one nested inside the other. In the inner loop for each iteration, I have the information needed to create a new instance of a certain type. I wanted to change the code for loops to use threads to collect all the objects in an ImmutableSet. However, I could not create a version that compiles and works. My sample program below illustrates my next attempt. It compiles, but one of the parameters is hard-coded.
How can I fix the stream below, so when I highlight Bar, I have both s and n variables?
class Bar {
private final String s;
private final Integer n;
Bar(String s, Integer n) {
this.s = s;
this.n = n;
}
}
public class Foo {
private static List<Integer> getList(String s) {
return Lists.newArrayList(s.hashCode());
}
Foo() {
ImmutableSet<Bar> set = ImmutableSet.of("foo", "bar", "baz")
.stream()
.flatMap(s -> getList(s).stream())
.map(n -> new Bar("", n))
.collect(ImmutableSet.toImmutableSet());
}
}
source
share