JDK8之后Lambda表达式,极大的简化了集合的操作,最近项目需要用到,特整理了一下几种用法。
先来一个对象
@Data
@AllArgsConstructor
public class Student {
private int no;
private String name;
private String classNo;
private int core;
}
添加maven 配置
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.5</version>
</dependency>
测试类
import lombok.extern.slf4j.Slf4j;
import java.util.*;
import java.util.stream.Collectors;
@Slf4j
public class TestStream {
public static void main(String [] args){
List<Student> studentList=new ArrayList<>();
studentList.addAll(Arrays.asList(
new Student(1,"111","12",30)
,new Student(2,"111","12",40)
,new Student(3,"111","12",50)
,new Student(4,"111","12",60)
,new Student(5,"333","33",70)
,new Student(6,"333","33",80)
,new Student(7,"333","44",90)
));
//按照年纪分类统计
Map<Optional<String>,List<Student>> map1= studentList.stream()
.collect(Collectors.groupingBy(o->Optional.ofNullable(o.getClassNo())));
printInfo(map1);
//按照年级统计数量
Map<Optional<String>,Long> map2= studentList.stream()
.collect(Collectors.groupingBy(o->Optional.ofNullable(o.getClassNo()),Collectors.counting()));
printInfo(map2);
//按照年级计算求和,数量等
Map<String, IntSummaryStatistics> map3= studentList.stream()
.collect(Collectors.groupingBy(Student::getClassNo,Collectors.summarizingInt(Student::getCore)));
printInfo(map3);
//按照姓名统计数量
Map<String, Map<String, Long>> map4= studentList.stream()
.collect(Collectors.groupingBy(Student::getClassNo,Collectors.groupingBy(Student::getName,Collectors.counting())));
printInfo(map4);
//按照姓名统计
Map<String, Map<String, List<Student>>> map5= studentList.stream()
.collect(Collectors.groupingBy(Student::getClassNo,Collectors.groupingBy(Student::getName)));
printInfo(map5);
//按照学号统计分数
Map<Integer,Integer> map7=studentList.stream().collect(Collectors.toMap(Student::getNo,Student::getCore));
printInfo(map7);
//按照学号统计分数,生成新的Map,指定Value的取值
Map<String,Integer> map8=studentList.stream().collect(Collectors.toMap(Student::getClassNo,Student::getCore,(v1,v2)->v1));
printInfo(map8);
//处理Key值位空的情况
studentList.add(new Student(3,"333",null,90));
Map<Optional<String>,Long> map6= studentList.stream()
.collect(Collectors.groupingBy(o->Optional.ofNullable(o.getClassNo()),Collectors.counting()));
printOptionInfo(map6);
//Optional null/空处理
log.info("option:{}", Optional.ofNullable(null).orElse("xx"));
log.info("option:{}", Optional.ofNullable("aa").orElse("xx"));
}
//打印方法
private static void printOptionInfo(Map<Optional<String>,Long> map) {
map.forEach((key, value) -> {
log.info("{}+{}+{}+{}",key.isPresent(), key.isPresent(),key.isEmpty(),key, value);
});
}
//打印方法
private static void printInfo(Map map) {
map.forEach((key, value) -> {
log.info("{}-{}", key, value);
});
}
}
欢迎交流,后续持续更新
本文暂时没有评论,来添加一个吧(●'◡'●)