0

For an example, I have a list (or set) into which the same method is to be done for each entry. This is increadibly easy with a lamba as such:

ingredientBaskets.forEach(this::processToMarmalade);

However I would like for the processToMarmalade method to return the amount of fruit pieces that could not be processed and these summed up in the end. I can do that easily by having the method sum up and return the number of errors.

What I'd like to have is basically something like:

int result = ingredientBaskets.forEach(this::processToMarmalade).sum();

some something. Or in other words something that does the same as this:

int result = 0;
for (final Basket basket: ingredientBaskets) {
     result += processToMarmalade(basket)
}
}

Is there a way to do that?

EDIT: As from the answers, List and Set would allow the usage of IntStream, which is one thing that I need. What however, if it's Iterable? This one does not have a stream, just a forEach.
Assume the original question, but also for the case of Iterable. Can the forEach sum it all up someway, or do I have to create a new List and fill it up with the contents of the Iterable first?

GregT
  • 1,039
  • 4
  • 14
  • 34
kumoyadori
  • 337
  • 2
  • 10
  • 21
  • You need do convert your stream to an ``IntStream`` which offers the ``sum`` method. – f1sh Nov 03 '17 at 10:30
  • Step 1: forget about the existence of `forEach`. Step 2: learn about [the other methods](https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#method.summary). – Holger Nov 03 '17 at 10:58

3 Answers3

4

What you are looking for is the mapToInt method (assuming processToMarmalade returns an int):

int result = ingredientBaskets.stream().mapToInt(this::processToMarmalade).sum();

If ingredientBaskets you have is an Iterable<?>, you can convert it to a stream like this:

StreamSupport.stream(ingredientBaskets.spliterator(), false)
             .mapToInt(this::processToMarmalade)
             .sum();
assylias
  • 321,522
  • 82
  • 660
  • 783
1
ingredientBaskets.stream()
    .mapToInt(this::processToMarmalade)
    .sum()
Eugene
  • 117,005
  • 15
  • 201
  • 306
0

I guess I would do it like this:

ingredientBaskets.stream().mapToInt(this::processToMarmalade).sum();
pwain
  • 279
  • 2
  • 7
  • 2
    Why do you post the same answer as the other two 6 minutes later? – Thomas Böhm Nov 03 '17 at 10:36
  • 1
    Because I clicked at answer. Wrote it down. I was not 100% sure. So I opened my eclipse and tested it before I pressed save to prevend a wrong answer. – pwain Nov 03 '17 at 10:40