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;
    }
}
Würgspaß
  • 4,660
  • 2
  • 25
  • 41
Suule
  • 2,197
  • 4
  • 16
  • 42

2 Answers2

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);
Eugene
  • 117,005
  • 15
  • 201
  • 306
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);
davidxxx
  • 125,838
  • 23
  • 214
  • 215
  • 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 Aug 23 '18 at 13:33
  • @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. – davidxxx Aug 23 '18 at 13:38
  • 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. – Kevin Cruijssen Aug 23 '18 at 13:47