To filter elements of a list based on a condition in Java, you can use the Stream API along with lambda expressions.
In this example,
numbers
with integer values.stream()
method to create a stream of elements from the list.filter
method along with a lambda expression to filter elements greater than a threshold value.import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int threshold = 3;
List<Integer> filteredNumbers = numbers.stream()
.filter(num -> num > threshold)
.collect(Collectors.toList());
System.out.println("Filtered list: " + filteredNumbers);
}
}
Filtered list: [4, 5]
In this example,
words
with string values.stream()
method to create a stream of elements from the list.filter
method along with a lambda expression to filter elements containing a specific substring.import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<String> words = Arrays.asList("apple", "banana", "cherry", "date", "elderberry");
String substring = "erry";
List<String> filteredWords = words.stream()
.filter(word -> word.contains(substring))
.collect(Collectors.toList());
System.out.println("Filtered list: " + filteredWords);
}
}
Filtered list: [cherry, elderberry]
In this tutorial, we learned How to Filter Elements of a List based on a Condition in Java language with well detailed examples.