Search data from a Stream

Harinath
1,356 views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

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
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// {...}
//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());
//{...}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content