2

I am trying to make myself more comfortable with Java 8 Stream api. Currently I want to translate something like as stream, but it seems I am still not comfortable enough, because I have no idea how to do this.

boolean isTrue = false;

for (Integer integer : intList) {
    if (integer > 10) {
        isTrue = true;
        break;
    }
}
0

2 Answers 2

13

All you care about is if at least one input from your list is bigger than 10, thus anyMatch:

boolean isTrue = intList.stream()
                        .anyMatch(x -> x > 10);
Sign up to request clarification or add additional context in comments.

7 Comments

can cause NPE ?
@VdeX I need some context to your question, please
sorry intList.stream() can cause NPE,isnt it?
@VdeX finally :) why not make it clear from the beginning? Optional.ofNullable(intList).orElse(Collections.emptyList()).anyMatch(x -> x > 10)
So sorry, yea I was too abstract :(
|
3
  • you iterate a List of Integer. So use Collection.stream()

  • you compare numeric value. So use Stream.mapToInt() to work with int rather than Integer that is more efficient. Here it doesn't change many things but if you change the stream to do some other numerical operations, you already use the correct way.

  • you value a boolean (result) as soon as a condition is met. Otherwise false I assume. So use Stream.anyMatch(Predicate).

So this corresponds :

boolean result =
intList.stream()
       .mapToInt(i-> i)
       .anyMatch(i-> i > 10);

3 Comments

Why the mapToInt() though to work with a primitive int instead of object Integer? The Integer will get unboxed to int anyway at i -> i > 10 (like in Eugene's answer) without it. And in your answer it still gets auto-unboxed at i -> i.
@Kevin Cruijssen Right. But suppose you modify the stream later to have other processings , some boxing operations could occur. Using mapToInt() here is more a way to write a robust code.
Hmm, hadn't thought about that. I still feel like it's a bit redundant in this case, but I can understand your reasoning behind it now.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.