Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access element of previous step in a stream or pass down element as "parameter" to next step?

What is a good way to access an element of a previous step of a stream?

The example here starts with a stream of parents (String) and flatMaps them to two children (Integer) for each parent. At the step where I am dealing with the Integer children (forEach) I would like to "remember" what the parent String was ('parentFromPreviousStep' compilation error).

The obvious solution is to introduce a holder class for a String plus an Integer and in the flatMap produce a stream of such holder objects. But this seems a bit clumsy and I was wondering whether there is a way to access a "previous element" in such a chain or to "pass down a parameter" (without introducing a special holder class).

    List<String> parents = new ArrayList();
    parents.add("parentA");
    parents.add("parentB");
    parents.add("parentC");

    parents.stream()
            .flatMap(parent -> {
                List<Integer> children = new ArrayList<>();
                children.add(1);
                children.add(2);
                return children.stream();
            }).forEach(child -> System.out.println(child + ", my parent is: ???" + parentFromPreviousStep));

Background: This actually happens in Nashorn with the idea to provide JavaScript scripting code for an application without having to deploy the Java application. This is why I do not want to introduce a special Java holder class for my two business objects (which are simplified here as String and Integer). [The Java code above can be written almost the same in Nashorn, and the stream functions are Java, not JavaScript.]

like image 703
StaticNoiseLog Avatar asked Oct 12 '16 08:10

StaticNoiseLog


1 Answers

Holger's comment to the question provides valuable information and leads to the following solution. The existence of SimpleImmutableEntry in the JDK solves the problem that creating a proprietary holder class was not an option for me in this situation. (This is a community wiki because Holger provided the answer.)

Stream.of("parentA", "parentB", "parentC")
.flatMap(parent -> Stream.of(
            new AbstractMap.SimpleImmutableEntry<>(1, parent),
            new AbstractMap.SimpleImmutableEntry<>(2, parent))
).forEach(child -> System.out.println(child.getKey() + ", my parent is: " + child.getValue()));
like image 199
2 revs, 2 users 73% Avatar answered Oct 13 '22 00:10

2 revs, 2 users 73%