Java8 使用 stream().map()提取List对象的某一列值及排重
List对象类(StudentInfo)
@Data @Builder @AllArgsConstructor @RequiredArgsConstructor public class StudentInfo implements Comparable<StudentInfo> { //名称 private String name; //性别 true男 false女 private Boolean gender; //年龄 private Integer age; //身高 private Double height; //出生日期 private LocalDate birthday; }
测试数据
//测试数据,请不要纠结数据的严谨性 List<StudentInfo> studentList = new ArrayList<>(); studentList.add(new StudentInfo("李小明",true,18,1.76,LocalDate.of(2001,3,23))); studentList.add(new StudentInfo("张小丽",false,18,1.61,LocalDate.of(2001,6,3))); studentList.add(new StudentInfo("王大朋",true,19,1.82,LocalDate.of(2000,3,11))); studentList.add(new StudentInfo("陈小跑",false,17,1.67,LocalDate.of(2002,10,18)));
提取某一列(以name为例)
//从对象列表中提取一列(以name为例) List<String> nameList = studentList.stream().map(StudentInfo::getName).collect(Collectors.toList());
提取age列并排重(使用distinct()函数)
//从对象列表中提取age并排重 List<Integer> ageList = studentList.stream().map(StudentInfo::getAge).distinct().collect(Collectors.toList());
Java8 使用 stream().sorted()对List集合进行排序
集合对像定义
集合对象以学生类(StudentInfo)为例,有学生的基本信息,包括:姓名,性别,年龄,身高,生日几项。
使用stream().sorted()进行排序,需要该类实现 Comparable 接口,该接口只有一个方法需要实现,如下:
public int compareTo(T o);
排序
//按年龄排序(Integer类型):使用年龄进行升序排序 List<StudentInfo> studentsSortName = studentList.stream().sorted(Comparator.comparing(StudentInfo::getAge)).collect(Collectors.toList()); //按年龄排序(Integer类型):使用年龄进行降序排序(使用reversed()方法) List<StudentInfo> studentsSortName = studentList.stream().sorted(Comparator.comparing(StudentInfo::getAge).reversed()).collect(Collectors.toList()); //按年龄排序(Integer类型): 使用年龄进行降序排序,年龄相同再使用身高升序排序 List<StudentInfo> studentsSortName = studentList.stream() .sorted(Comparator.comparing(StudentInfo::getAge).reversed().thenComparing(StudentInfo::getHeight)) .collect(Collectors.toList());
Java8 使用 stream().filter()过滤List对象(查找符合条件的对象集合)
//查找身高在1.8米及以上的男生 List<StudentInfo> boys = studentList.stream().filter(s->s.getGender() && s.getHeight() >= 1.8).collect(Collectors.toList());