Java stream filter()
Java流提供了一个方法filter(),用于在给定谓词的基础上过滤流元素。假设只想获取列表中的偶数个元素,则可以在filter方法的帮助下轻松地做到这一点。
此方法将谓词作为参数并返回由结果元素组成的流。
签名
Stream filter()方法的签名如下:
Stream<T> filter(Predicate<? super T> predicate)
参数
predicate: 它将谓词引用作为参数。谓词是功能接口。因此,您也可以在此处传递lambda表达式。
返回
它返回一个新stream。
Java Stream filter()示例
在下面的示例中,我们正在获取和迭代过滤后的数据。
import java.util.*;
class Product{
int id;
String name;
float price;
public Product(int id, String name, float price) {
this.id = id;
this.name = name;
this.price = price;
}
}
public class JavaStreamExample {
public static void main(String[] args) {
List<Product> productsList = new ArrayList<Product>();
//Adding Products
productsList.add(new Product(1,"HP Laptop",25000f));
productsList.add(new Product(2,"Dell Laptop",30000f));
productsList.add(new Product(3,"Lenevo Laptop",28000f));
productsList.add(new Product(4,"Sony Laptop",28000f));
productsList.add(new Product(5,"Apple Laptop",90000f));
productsList.stream()
.filter(p ->p.price> 30000) // filtering price
.map(pm ->pm.price) // fetching price
.forEach(System.out::println); // iterating price
}
}
输出:
Java Stream filter()示例2
在以下示例中,我们将过滤后的数据作为列表来获取。
import java.util.*;
import java.util.stream.Collectors;
class Product{
int id;
String name;
float price;
public Product(int id, String name, float price) {
this.id = id;
this.name = name;
this.price = price;
}
}
public class JavaStreamExample {
public static void main(String[] args) {
List<Product> productsList = new ArrayList<Product>();
//Adding Products
productsList.add(new Product(1,"HP Laptop",25000f));
productsList.add(new Product(2,"Dell Laptop",30000f));
productsList.add(new Product(3,"Lenevo Laptop",28000f));
productsList.add(new Product(4,"Sony Laptop",28000f));
productsList.add(new Product(5,"Apple Laptop",90000f));
List<float> pricesList = productsList.stream()
.filter(p ->p.price> 30000) // filtering price
.map(pm ->pm.price) // fetching price
.collect(Collectors.toList());
System.out.println(pricesList);
}
}
输出: