📜  Java8 Stream Filter

📅  最后修改于: 2020-10-13 02:17:17             🧑  作者: Mango

Java流过滤器

Java流提供了一个方法filter()根据给定的谓词来过滤流元素。假设您只希望获得列表中的偶数个元素,则可以借助filter方法轻松地做到这一点。

此方法以谓词为参数,并返回由结果元素组成的流。

Signature(签名)

Stream filter()方法的签名如下:

Stream filter(Predicate predicate)

参数

谓词:将谓词引用作为参数。谓词是功能接口。因此,您也可以在此处传递lambda表达式。

返回

它返回一个新的流。

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 productsList = new ArrayList();
//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
}
}

输出:

90000.0

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 productsList = new ArrayList();
//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 pricesList =productsList.stream()
.filter(p ->p.price> 30000)// filtering price
.map(pm ->pm.price)// fetching price
.collect(Collectors.toList());
System.out.println(pricesList);
}
}

输出:

[90000.0]