Lambda表达式算是Java8的最重要的一个特性,学会使用它,能使我们的代码更加简洁、漂亮、优雅
理论不多阐述,今天我们汇总一下基于Lamdba 表达式的示例,希望可以帮助到新手,大神勿喷!
示例一
场景:一个List集合,需要单独把Student对象的Id抽取封装到一个List
实现:
List studentIds = studentList.stream().map(Student::getId).collect(Collectors.toList());
拓展:谷歌Guava 包 提供 Lists.transform 还有更简洁的写法
List studentIds = Lists.transform(studentList, Student::getId);
示例二
场景:基于Student对象,抽取其学号,姓名构建K,V 结构的HashMap
实现:
HashMap studentMap = studentList.stream().collect(HashMap::new, (map, student) -> map.put(student.getId(), student.getName()), HashMap::putAll);扩展:
studentMap.putAll(studentList.stream().collect(Collectors.toMap(Student::getId, Student::getName)));
示例三
场景:List studentList 基于性别 gender 分组 构建成 Map> studentMap
实现:
Map>studentMap = studentList.stream().collect(Collectors.groupingBy(Student::getGender));
示例四
场景:List studentList 基于分数score排序
实现:
studentList.stream().sorted(Comparator.comparingInt(Student::getScore));
扩展:默认是正向排序,倒序如下
studentList.stream().sorted(Comparator.comparingInt(Student::getScore).reversed());
示例五
场景:K,V结构HashMapstudentMap 根据key 排序
实现:
studentMap.entrySet().stream().sorted(Entry.comparingByKey());
扩展:基于value排序
studentMap.entrySet().stream().sorted(Entry.comparingByValue());
示例六
场景:List studentList 累计玩家的得分Score
实现:
int total = studentList.stream().mapToInt(Student::getScore).sum();扩展:获取分数有关的整个信息 包括最大、最小、平均分等
IntSummaryStatistics summary = studentList.stream().mapToInt(Student::getScore) .summaryStatistics();
summary.getMax(); //最大
summary.getMin(); //最小
summary.getSum(); //总分数
summary.getAverage(); //平均数
summary.getCount(); //总个数
以上6个实例,虽然简单,但却很实用,实际工作中一定会用到,如果还不会得抓紧时间建议收藏学习起来。关注我,后续会给您带来更多实用 有意思的内容