Normally, before Java 8, when we want to filter a List, we will iterate through the List and base on the condition we want to filter, we can have a new List on demand.
For example, I have a List containing some student names as below:
1 2 3 4 |
List<String> names = new ArrayList<>(); names.add("Thanh"); names.add("Khanh"); names.add("Tan"); |
Now, I want to filter above List to have a new List containing the student names only start with the letter “T”, then I will code as below:
1 2 3 4 5 6 7 8 |
List<String> namesStartWithT = new ArrayList<>(); for (String s : names) { if (s.startsWith("T")) { namesStartWithT.add(s); } } System.out.println(namesStartWithT); |
Result:
Since Java 8, we have another better way to do this by using Stream and Lambda Expression. Detail is: we will create new Stream object from our List object and use filter() method in this Stream object to filter.
1 |
Stream stream = names.stream().filter(s -> s.startsWith("T")); |
The argument of filter() method is Predicate interface, a Functional interface, and this method is an intermediate operation. Then we need to add more method for a terminal operation to complete a Stream pipeline.
Here, after filtering, I will collect all the result into a List object by using terminal method collect() of Stream as below:
1 2 3 4 5 |
List list = names.stream() .filter(s -> s.startsWith("T")) .collect(Collectors.toList()); System.out.println(list.toString()); |
When running the code, the result will be same as above.