Search data from a Stream
Harinath
4,239 views
Search for the data by using the methods of Stream classes... findFirst findAny anyMatch allMatch noneMatch
Methods ending with "Match" returns boolean value. Methods starting with "find" returns return Optional (we discuss Optional in further playgrounds)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// {
import java.util.stream.IntStream;
import java.util.OptionalInt;
public class Main {
public static void main(String[] args) {
// }
//returns false
boolean anyMatch
= IntStream.of(-6, -7, -5, -2, -8, -1, -9).anyMatch(value -> value > 0);
System.out.println("anyMatch(value -> value > 0): " + anyMatch);
//returns false
boolean allMatch
= IntStream.of(-6, -7, -5, -2, -8, -1, -9).allMatch(value -> value > 0);
System.out.println("allMatch(value -> value > 0): " + allMatch);
//returns true
boolean noneMatch
= IntStream.of(-6, -7, -5, -2, -8, -1, -9).noneMatch(value -> value > 0);
System.out.println("noneMatch(value -> value > 0): " + noneMatch);
//returns 5
OptionalInt optValue = IntStream.of(-6, -7, 5, -2, -8, 1, 9)
.filter(value -> value > 0)
.findFirst();
System.out.println("First matching value > 0 is " + optValue.getAsInt());
//{
}
}
//}
Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.