lambda表达式案例(持续更新)

来源:互联网 发布:阿里大数据平台 编辑:程序博客网 时间:2024/06/01 18:28

1、统计Map里某种value的出现次数(总和/平均数/最大值等)

(1)IntSummaryStatistics

IntSummaryStatistics summary = cStatusMap.entrySet().stream()                .filter(x -> x.getValue() == Status.OK).collect(Collectors.summarizingInt(Map.Entry::getValue));int count = (int)summary.getCount();

(2)原始类型流(如IntStream):如果只需获得一次类似方法的结果,使用原始类型流更简洁易懂,缺点在于因为是流所以只能使用一次

IntStream intStream = cStatusMap.entrySet().stream()                .filter(x -> x.getValue() != Status.OK).mapToInt(Map.Entry::getValue);int count = (int)intStream.count();


2、复用判定条件:在lambda表达式中反复使用同样的判定条件会让表达式越来越长,如果把它设为变量就可以很好地实现复用

Predicate<String> startsWithJ = (n) -> n.startsWith("J");Predicate<String> threeLetterLong = (n) -> n.length() == 3;Stream.of("Java", "Scala", "C++", "Haskell", "Lisp").filter(startsWithJ.or(threeLetterLong)).forEach(System.out::println);


3、通过某条件将集合分组(groupingBy)

Map<String, List<User>> collect = list.stream().collect(Collectors.groupingBy(x -> x.getStatus()));

4、List转map(Collectors.toMap)

Map<Integer,Person> map = personList.stream().collect(Collectors.toMap((Person::getId),(value->value)));


5、筛选出符合条件的某值

Integer unitPrice = list.stream().filter(x -> x.getId() == orderPo.getSeriesId()).map(LivePo::getUnitPrice).findFirst().orElse(null);










1 0