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为例)
List<String> nameList = studentList.stream().map(StudentInfo::getName).collect(Collectors.toList());
//从对象列表中提取age并排重
List<Integer> ageList = studentList.stream().map(StudentInfo::getAge).distinct().collect(Collectors.toList());
//查找身高在1.8米及以上的男生
List<StudentInfo> boys = studentList.stream().filter(s->s.getGender() && s.getHeight() >= 1.8).collect(Collectors.toList());
集合对像定义
集合对象以学生类(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());
//List–long求和
List<Long> longList = Arrays.asList(1L, 2L, 3L, 4L);
Long longSum = longList.stream().mapToLong(Long::longValue).sum();
System.out.println(longSum);
//使用reduce
long longSumReduce = longList.stream().reduce(Long::sum).orElse(0L);
System.out.println(longSumReduce);
//list—Double求和
List<Double> doubleList = Arrays.asList(1.0, 2.0, 3.0, 14.0);
Double doubleSum = doubleList.stream().mapToDouble(Double::doubleValue).sum();
System.out.println(doubleSum);
//list–T 泛型求和
long num = list.stream().mapToLong(User::getNum).sum();
Double cnt= list.stream().mapToDouble(ScreenSales::getCnt).sum();
参考链接:
https://developer.ibm.com/zh/articles/j-lo-java8streamapi/