In this source code example, we show how to use forEach() method to filter list in Java with examples.
Java 8 forEach Filtering Example
In this example, we filter a list of strings and print the filtered list to the console. Only strings having greater than equal to three characters are shown.
import java.util.ArrayList;
import java.util.List;
public class JavaForEachListFilter {
public static void main(String[] args) {
List progLangs = new ArrayList<>();
progLangs.add("Java");
progLangs.add("C");
progLangs.add("C++");
progLangs.add("Python");
progLangs.add("GoLang");
progLangs.stream().filter(item -> (item.length() >= 3)).forEach(System.out::println);
}
}
Output:
Java C++ Python GoLang