In this tutorial, we will show you few Java 8 examples to demonstrate the use of Streams filter()
, collect()
, findAny()
and orElse()
1. Streams filter() and collect()
1.1 Before Java 8, filter a List
like this :
BeforeJava8.java
package com.mkyong.java8;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class BeforeJava8 {
public static void main(String[] args) {
List<String> lines = Arrays.asList("spring", "node", "mkyong");
List<String> result = getFilterOutput(lines, "mkyong");
for (String temp : result) {
System.out.println(temp); //output : spring, node
}
}
private static List<String> getFilterOutput(List<String> lines, String filter) {
List<String> result = new ArrayList<>();
for (String line : lines) {
if (!"mkyong".equals(line)) { // we dont like mkyong
result.add(line);
}
}
return result;
}
}
Output
spring
node
1.2 The equivalent example in Java 8, stream.filter()
to filter a List
, and collect()
to convert a stream into a List
.
NowJava8.java
package com.mkyong.java8;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class NowJava8 {
public static void main(String[] args) {
List<String> lines = Arrays.asList("spring", "node", "mkyong");
List<String> result = lines.stream() // convert list to stream
.filter(line -> !"mkyong".equals(line)) // we dont like mkyong
.collect(Collectors.toList()); // collect the output and convert streams to a List
result.forEach(System.out::println); //output : spring, node
}
}
Output
spring
node