24

With Collection everything is clear, but what about the following:

There is an object with a count() method and a getPart(int i) method. So extracting all objects leads to the following boilerplate code:

List<Part> result = new ArrayList<Part>();
for (int i = 0, i < object.count(), i++) {
    result.add(object.getPart(i));        
}
return result.stream(); 

Is there any standard way to pass just 2 producers: () -> object.count() and (int i) -> object.getPart(i) to create a stream? Like this:

SomeUtil.stream(object::count, object::getPart);
Cherry
  • 31,309
  • 66
  • 224
  • 364

1 Answers1

41

Try this:

IntStream.range(0, object.count()).mapToObj(object::getPart);
MBec
  • 2,172
  • 1
  • 12
  • 15
  • 4
    I lost track of how many times the solution to a "how do I create a stream from this weird thing"-problem was an `IntStream` solution! :D – Olle Kelderman Feb 28 '17 at 12:17