2

I have a program that runs chaining methods

MyObject o = MyObject.getInstance().method1().method2().go();

Now, this instance returns multiple lines of data,

I can execute them in a loop but I would rather do this:

MyObject o = MyObject.getInstance().foreach().method1().method2().go();

I.e used a for each

is it possible in Java to do this?

meditat
  • 1,197
  • 14
  • 33
Maaz Soan
  • 113
  • 2
  • 8

2 Answers2

2

You can do this in Java 8, assuming getInstance() returns a stream:

MyObject.getInstance().forEach(item-> item.method1().method2().go() );

See the streaming API documentation here: https://docs.oracle.com/javase/tutorial/collections/streams/

Oleksi
  • 12,947
  • 4
  • 56
  • 80
0

No, foreach does not return an iterator.

However, map and flatMap provide return values which can be iterated over. See https://stackoverflow.com/a/26684710/553865

Mike Slinn
  • 7,705
  • 5
  • 51
  • 85