Stream
Stream(流)是一个来自数据源的元素队列并支持聚合操作;
map
map 方法用于映射每个元素到对应的结果;
Collectors
Collectors 类实现了很多归约操作,例如将流转换成集合和聚合元素。Collectors 可用于返回列表或字符串。
此处假设我们已经获得了一个学生对象的集合studentList。
获取对象list集合中的某个属性使其成为一个新的集合
List studentCodeList = studentList.stream().map(Student::getStudentCode).collect(Collectors.toList());
清空对象list集合中的某个属性的值并返回结果
studentList.stream().map(v->
{
v.setStudentCode("");
return v;
}).collect(Collectors.toList());
list集合转为map集合,从学生对象中取出一个字段的值作为map的key,学生对象则为value
Map<String, Student> studentMap = studentList.stream().collect(Collectors.toMap(Student::getStudentCode, Function.identity()));
Student student = studentMap.get("code2");
上面的list转为map时,key出现重复就会报错,要去重。给出key重复时,使用哪个key作为主键,以下代码中的(key1, key2) -> key1)代表key1和key2键重复时返回key1做主键
Map<String, Student> studentMap = studentList.stream().collect(Collectors.toMap(Student::getStudentCode, Function.identity(), (key1, key2) -> key1));
Student student = studentMap.get("code2");
list集合转为map集合,从学生对象中取出一个字段的值作为map的key,取出另一个字段的值作为map的value
Map<String, String> studentMap = studentList.stream().collect(Collectors.toMap(Student::getStudentCode, Student::getStudentId));
String studentId = studentMap.get("code2");
获取list集合中前三个元素 组成新的集合
List<Student> newStudentList = studentList.stream().limit(3).collect(Collectors.toList());
跳过list集合中前三个元素 剩余的元素组成新的集合
List<Student> newStudentList = studentList.stream().skip(3).collect(Collectors.toList());
去除list集合中重复元素 剩余的元素组成新的集合
List<Student> newStudentList = studentList.stream().distinct().collect(Collectors.toList());
过滤出符合条件的元素 组成新的集合
List<Student> newStudentList = studentList.stream().filter(s -> s.getId().equals("id1")).collect(Collectors.toList());
List转Map、以某个属性分组
Map<Integer, List> map = list.stream().collect(Collectors.groupingBy(Student::getStudentId));
List集合进行排序,此处以Student类中的id字段为排序标准
List<Student> studentList1 = studentList.stream().sorted(Comparator.comparing(Student::getId)).collect(Collectors.toList()); // 升序
List<Student> studentList2 = studentList.stream().sorted(Comparator.comparing(Student::getId).reversed()).collect(Collectors.toList()); // 降序
List<Student> studentList1 = studentList.stream().sorted(Comparator.comparing(Student::getId,Comparator.nullsFirst(BigDecimal::compareTo)).collect(Collectors.toList()); // 升序并将null值放前面
List<Student> studentList1 = studentList.stream().sorted(Comparator.comparing(Student::getId,Comparator.nullsLast(BigDecimal::compareTo)).collect(Collectors.toList()); // 升序并将null值放后面
List<Student> studentList2 = studentList.stream().sorted(Comparator.comparing(Student::getId,Comparator.nullsLast(BigDecimal::compareTo).reversed()).collect(Collectors.toList()); // 降序并将null值放前面
List<Student> studentList2 = studentList.stream().sorted(Comparator.comparing(Student::getId,Comparator.nullsFirst(BigDecimal::compareTo).reversed()).collect(Collectors.toList()); // 降序并将null值放后面