Close

Java 8 Streams - Stream.filter Examples

Java 8 Streams Java Java API 


Interface:

java.util.stream.Stream

java.lang.AutoCloseableAutoCloseablejava.util.stream.BaseStreamBaseStreamjava.util.stream.StreamStreamLogicBig

Method:

Stream<T> filter(Predicate<? super T> predicate)

Returns a stream consisting of the elements of this stream that match the given predicate.


Examples


package com.logicbig.example.stream;

import java.util.stream.Stream;

public class FilterExample {

public static void main(String... args) {
Stream<String> s = Stream.of("one", "two", "three", "four");
Stream<String> s2 = s.filter(e -> e.endsWith("e"));
s2.forEach(System.out::println);
}
}

Output

one
three




    @Override
public User loginUser (User user) {
Optional<User> loggedInUser = users.stream()
.filter(u -> validateUser(u, user))
.findAny();
return loggedInUser.isPresent() ? loggedInUser.get() : null;
}

private static boolean validateUser (User existingUser, User user) {
return existingUser.getEmailAddress()
.equals(user.getEmailAddress())
&& existingUser.getPassword()
.equals(user.getPassword());
}
Original Post




This example shows that updating an external variable from behavioral parameter can lead to non-determinist result.

package com.logicbig.example;


import java.util.stream.IntStream;

public class StatefulExample2 {
private static int count = 0;

public static void main (String[] args) {
for (int i = 0; i < 5; i++) {
process();
}
}

private static void process () {
count = 0;

IntStream stream = IntStream.range(1, 1000);
//finding the sum of even numbers
int sum = stream.parallel()
.filter(i -> {
boolean b = i % 2 == 0;
if (b) {
count++;//updating count hence making it stateful.
}
return b;
})
.sum();

System.out.printf("sum :%d count:%d%n", sum, count);
}
}

Output

sum :249500  count:399
sum :249500 count:411
sum :249500 count:456
sum :249500 count:456
sum :249500 count:456
Original Post




This example shows alternative way to do the same thing as above example but in a stateless manner.

package com.logicbig.example;

import java.util.stream.IntStream;


public class StatefulFixExample2 {
public static void main (String[] args) {
for (int i = 0; i < 5; i++) {
process();
}
}

private static void process () {
IntStream stream = IntStream.range(1, 1000);

//finding the even numbers
int[] even = stream.parallel()
.filter(i -> i % 2 == 0)
.toArray();

//finding sum
int sum = IntStream.of(even).parallel().sum();

System.out.printf("sum :%d count:%d%n", sum, even.length);
}
}

Output

sum :249500  count:499
sum :249500 count:499
sum :249500 count:499
sum :249500 count:499
sum :249500 count:499
Original Post




See Also