List<Student> studentList = Lists.newArrayList(new Student("路飞", 22, 175), new Student("红发", 40, 180),
new Student("白胡子", 50, 185), new Student("白胡子", 60, 185));
//最大值
Optional<Student> maxStudent = studentList.stream().max(Comparator.comparingInt(Student::getHeight));
//最小值
Optional<Student> minStudent = studentList.stream().min(Comparator.comparingInt(Student::getHeight));
//平均值
Double avgAge = studentList.stream().collect(Collectors.averagingInt(Student::getAge));
//统计,包括数量,和,最大最小值
IntSummaryStatistics summaryStatistics = studentList.stream().collect(Collectors.summarizingInt(Student::getAge));
long count = summaryStatistics.getCount();
int max = summaryStatistics.getMax();
int min = summaryStatistics.getMin();
long sum = summaryStatistics.getSum();
//连接收集器
//直接连接
String join1 = studentList.stream().map(Student::getName).collect(Collectors.joining());
//逗号
String join2 = studentList.stream().map(Student::getName).collect(Collectors.joining(","));
//toList
List<String> nameList = studentList.stream().map(Student::getName).collect(Collectors.toList());
//toSet
Set<String> nameSet = studentList.stream().map(Student::getName).collect(Collectors.toSet());
//去重
List<Student> uniqueStudentList = studentList.stream().distinct().collect(Collectors.toList());
//按属性去重
List<Student> attrUniqueStudentList = studentList.stream().collect(collectingAndThen(toCollection(() -> new TreeSet<>(Comparator.comparing(Student::getName))), ArrayList::new));
//toMap
Map<String, Integer> studentMap = studentList.stream().collect(Collectors.toMap(Student::getName, Student::getAge));
public class Student {
private String name;
private Integer age;
private Integer height;
public Student(String name, Integer age, Integer height) {
this.name = name;
this.age = age;
this.height = height;
}
public Student() {
}
public Integer getHeight() {
return height;
}
public void setHeight(Integer height) {
this.height = height;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
标签:name,stream,public,collect,studentList,Student,使用,JAVA8
From: https://www.cnblogs.com/abowu/p/18335230