参考Java8 使用 stream().filter()过滤List对象(查找符合条件的对象集合)
在Java8及以上版本中,使用stream().filter()来过滤一个List对象,查找符合条件的对象集合。
1.maven项目添加依赖
<properties>
<java.version>1.8</java.version>
<alibaba.fastjson.version>1.2.76</alibaba.fastjson.version>
<projecglombok.version>1.18.20</projecglombok.version>
</properties>
<dependencies>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${alibaba.fastjson.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${projecglombok.version}</version>
</dependency>
</dependencies>
2.有实体类如下,实现Comparable接口,实现接口的compareTo()方法
import java.time.LocalDate;
import lombok.Builder;
import lombok.Data;
@Data
@Builder
public class StudentInfoimplements Comparable<StudentInfo> {
private String name;
private Integer age;
private Boolean gender;
private Double height;// 身高
private LocalDate birthday;
}
3. 实现过滤
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSONObject;
public class ListFilter {
private static Logger logger = LoggerFactory.getLogger(ListFilter.class);
public static void main(String[] args) {
listFilterTest();
}
public static void listFilterTest() {
// 测试数据
List<StudentInfo> studentList =new ArrayList<>();
studentList.add(StudentInfo.builder().name("李小明").gender(true).age(18).height(1.76).birthday(LocalDate.of(2001,3,23)).build());
studentList.add(StudentInfo.builder().name("张小丽").gender(false).age(18).height(1.61).birthday(LocalDate.of(2001,6,3)).build());
studentList.add(StudentInfo.builder().name("王大朋").gender(true).age(19).height(1.82).birthday(LocalDate.of(2000,3,11)).build());
studentList.add(StudentInfo.builder().name("陈小跑").gender(false).age(17).height(1.67).birthday(LocalDate.of(2002,10,18)).build());
logger.info("before filter studentInfos is {}", JSONObject.toJSON(studentList));
// 查找身高在1.8米及以上的男生
List<StudentInfo> boys = studentList.stream().filter(s -> s.getGender() && s.getHeight() >=1.8).collect(Collectors.toList());
// 输出查找结果
logger.info("after filter studentInfos is {}", JSONObject.toJSON(boys));
}
}
4.运行方法,log如下
23:44:18.324 [main] INFO com.example.utilsDemo.ListFilter - before filter studentInfos is [{"birthday":"2001-03-23","gender":true,"name":"李小明","age":18,"height":1.76},{"birthday":"2001-06-03","gender":false,"name":"张小丽","age":18,"height":1.61},{"birthday":"2000-03-11","gender":true,"name":"王大朋","age":19,"height":1.82},{"birthday":"2002-10-18","gender":false,"name":"陈小跑","age":17,"height":1.67}]
23:44:18.350 [main] INFO com.example.utilsDemo.ListFilter - after filter studentInfos is [{"birthday":"2000-03-11","gender":true,"name":"王大朋","age":19,"height":1.82}]
|