0

Say I have two streams:

Stream<String> ids = Stream.of("id1","id2","id3","id4","id5");
Stream<MyObj> objects = Stream.of(new MyObj(null, "some data"), new MyObj(null, "some other data");

Now I would like to update my objects stream with the data from ids. The result whould be equivalent to the following Stream:

Stream<MyObj> objects = Stream.of(new MyObj("id1", "some data"), new MyObj("id2", "some other data");

I thus wonder if there is a way to consume both streams, one element at the time. I imagine some kind of "DoubleConsumer" (nothing to do with double) of the sort:

Stream<MyObj> result = DoubleConsumer.of(ids, objects)
                          .map((id, myobj) -> combine(id, myobj));

MyObj combine(String id, MyObj myobj) {
  myobj.set(id);
  return myobj;
}

Any idea how to achieve something like this?

Update

I know that I can solve this in the case of list with some double loop, or with FuncionalJava's zipfunction. However the question is how to do this with Java Streams.

Nicola Ambrosetti
  • 2,567
  • 3
  • 22
  • 38

1 Answers1

0

Do you want Stream.map. eg.

Stream<MyObj> objs = ids.map(id->new MyObj(id, "some data"));

This does exactly what op wants. Then if they want to update the values of the objects they can afterwards, and the objects know their id so that can be gotten.

If they want to "zip" two streams, they should check the existing answers.

matt
  • 10,892
  • 3
  • 22
  • 34