JDK8 stream常用方法(持续更新)

List list = new ArrayList<>();
//根据age对list分组
Map> groupByAge = list.stream().collect(Collectors.groupingBy(People::getAge));
//根据age进行排序(reserve倒序)
List peopleListSorted = list.stream().sorted(Comparator.comparing(People::getAge).reversed()).collect(Collectors.toList());
//提取age,并排序
List ageList = list.stream().map(People::getAge).distinct().sorted().collect(Collectors.toList());
//提取年龄大于20的people
List olderThan20 = list.stream().filter(e->Integer.parseInt(e.getAge()) > 20).collect(Collectors.toList());
//累加
BigDecimal totalMoney = list.stream().map(People::getMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
//查询
People people = list.stream().filter(e->e.getAge().equals("20")).findFirst().orElse(null);
//List -> Map (name,people)
Map map = list.stream().collect(Collectors.toMap(People::getName,n->n));

对于深度嵌套的语句,可能需要多次判空,才能保证代码的健壮性,但是用if来实现,会有一堆的if语句,java8通过optinal比较优雅的解决了这个问题。
举个例子:
String isocode = user.getAddress().getCountry().getIsocode().toUpperCase();


用if判空

if (user != null) {
    Address address = user.getAddress();
    if (address != null) {
        Country country = address.getCountry();
        if (country != null) {
            String isocode = country.getIsocode();
            if (isocode != null) {
                isocode = isocode.toUpperCase();
            }
        }
    }
}

用optional实现:

String isocode = Optional.ofNullable(user)
  .flatMap(User::getAddress)
  .flatMap(Address::getCountry)
  .map(Country::getIsocode)
  .orElse("default");

 

你可能感兴趣的:(JDK8 stream常用方法(持续更新))