0

I'm not sure if a question was already asked. I'm still new to Java's Stream API and Google's Guava.

I would like to use Java's Stream API to transform or map one object to another one item at a time. It seems like this is different than collect. It seems like collect would convert all items in the stream when it's called instead of one at a time. Ideally, I would like to provide an iterable that allows one item to be converted when something like next() is called.

Maybe it would look something like this:

private Iterable<ObjectA> getIterable(Iterable<ObjectB> itemsToConvert) {
  return itemsToConvert.map(mappingFunction);
}

public static void main(String[] args) {
  Iterable<ObjectA> myIterable = getIterable(itemsFromSomewhere);
  // do the conversion here
  ObjectA myItem = myIterable.next();
}

Is there a way to do this in Java using the Stream API? If not, is there a way to do this using Google's Guava?

Erik
  • 503
  • 1
  • 7
  • 26

1 Answers1

1

Oh you want to hook into the Iterator.next method. I don't think that is possible. You could however manipulate myItem since you got the reference you need e.g.

 ObjectA myItem = myIterable.next();
 manipulateObject(myItem); // change stuff do stuff

However, since you want the next() method to convert the next item in the iterator, you should implement your own Iterator and override it like it is explained here : https://stackoverflow.com/a/5849625/4467208

Community
  • 1
  • 1
Murat Karagöz
  • 35,401
  • 16
  • 78
  • 107
  • 1
    The pseudo code doesn't solve my problem but the link you gave does – Erik Feb 15 '17 at 15:10
  • For the purpose of quality here on stackoverflow, I recommend you write your own answer and check it as the accepted one, or edit the answer from @Murat K, but leave it as the accepted answer. – Wrench Feb 15 '17 at 17:02