0

I was trying to achieve something like this using lambdas. However, "i" has to be final.

int i = 1;
for (Object obj : list) {
 if (something) {
  i++;
 }
}

edit:

But what if I wanted to add, let's say, a value that is different from object to object?

int i = 1;
for (Object obj : list) {
   if (something) {
      otherMethod(i);
      i += obj.getValue();
   }
}
1
  • 3
    short answer is, if you are thinking how to combine functional style with mutation, it's already a fatal starting point. Commented Feb 24, 2018 at 17:32

2 Answers 2

8

You can do it like this instead:

int i = 1 + (int)list.stream().filter(something).count();

where something is the criteria to filter.

Sign up to request clarification or add additional context in comments.

8 Comments

Thanks for answering my question! But what if I wanted to add, let's say, a value that is different from object to object?
Then you can use the map intermediate operation.
What exactly do you want to achieve ? To extract some type of value from each object ? And sum it or?
Yea, get a Value from every object in a list and sum it - to be exact, I want to loop through the list, and add to the sume for every entry, after calling another method with the current sum. Sorry for the bad original Question - I edited it.
you should avoid side effects when working with streams. can you show the definition of otherMethod and the type returned from getValue.
|
1

As in the first answer written to count the elements, you first filter, then reduce (with count()).

list.stream().filter(obj -> something).count();

But if do not want to count the items, but use instead some value depending on the object, you should first map the stream to the intermediate values, and reduce them with e.g. sum.

list.stream()
    .filter(obj -> something)
    .mapToInt(obj -> obj.getValue())
    .sum()

You should never modify anything while using streams. (forEach can be an exception).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.