stream().collect():
@Test
public void CollectorsTest2() {
List<Student> studentList = new ArrayList<>();
Student student = new Student();
student.setId(1);
student.setName("张三");
student.setClassId("Chinese");
student.setGrade(95.0);
studentList.add(student);
student = new Student();
student.setId(2);
student.setName("李四");
student.setClassId("Chinese");
student.setGrade(96.0);
studentList.add(student);
student = new Student();
student.setId(3);
student.setName("王五");
student.setClassId("Chinese");
student.setGrade(93.5);
studentList.add(student);
//获取张三的成绩,stream().filter替代for循环, 查找集合中的第一个对象
Optional<Student> rStudent = studentList.stream().filter(x -> "张三".equals(x.getName())).findFirst();
System.out.println(rStudent.get().getName() + "," + rStudent.get().getGrade());
//返回集合
List<Student> students = studentList.stream().filter(x -> "张三".equals(x.getName()) || "李四".equals(x.getName()) ).collect(Collectors.toList());
//根据id分组
Map<Integer, List<Student>> studentMap = studentList.stream().collect(Collectors.groupingBy(Student::getId));
//获取最高成绩,最低成绩,总分,平均分,统计条数
DoubleSummaryStatistics statistics = studentList.stream().collect(Collectors.summarizingDouble(Student::getGrade));
double maxGrade = statistics.getMax();
double minGrade = statistics.getMin();
double sum = statistics.getSum();
double average = statistics.getAverage();
long count = statistics.getCount();
System.out.println("maxGrade="+ maxGrade + ",minGrade=" + minGrade + "sum=" + sum+ ",average=" + average + ",count=" + count);
//List<Student> -> toMap 去重,(oldValue, newValue)->oldValue 取原来的值,(oldValue, newValue)->newValue 取新值
Map<String, Object> nameMap = new HashMap<>();
if (!studentList.isEmpty()) {
nameMap = studentList.stream().collect(Collectors.toMap(Student->Student.getName(), Student->Student.getGrade(), (oldValue, newValue)->oldValue));
}
}
//list转map
Map<String,Student> studentMap = studentList.stream().collect(Collectors.toMap(student-> student.getId().toString(), Function.identity(), (oldValue, newValue) -> oldValue));
//map转lis
studentMap.values().stream().collect(Collectors.toList())
//排序,升序
studentList.sort((o1, o2) -> {return o1.getGrade-o2.getCrade});
//遍历
studentList.forEach(student -> {
System.out.println(student.getName());
});
stream().map():
List<Map<String, Object>> list = new ArrayList<>();
Map<String, Object> map = new HashMap<>();
map.put("id", "1");
map.put("name", "张三");
list.add(map);
map = new HashMap<>();
map.put("id", "2");
map.put("name", "李四");
list.add(map);
//以逗号分隔的字符串
String ids = list.stream().map(stringObjectMap -> stringObjectMap.get("id").toString()).collect(Collectors.joining(","));
System.out.println("ids="+ids); //1,2
实体类:
public class Student {
private Integer id;
private String name;
private String classId;
private Double grade;
Getter and Setter...
}