Collection of a set of objects from nested threads

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)) // I need to use s here, not hard-code
            .collect(ImmutableSet.toImmutableSet());
  }
}
+4
source share
1 answer

It looks like you are looking for something like:

.flatMap(s -> getList(s).stream().map(n -> new Bar(s, n)))

map getList(s).stream(), , , .

, getList(s).stream(). , , , flatMap, Stream<R>, .

+6

Source: https://habr.com/ru/post/1695530/


All Articles