Java8常用操作

Mars 2019年11月02日 27次浏览

stream流式表达式

stream高级特性

https://www.jianshu.com/p/e5c5a5e33e44

map一对一映射

    //a里面的元素全部加1
    List a = new ArrayList(l);
    for (int i = 0; i < l; i++) {
        a.add(Math.random());
    }
    a.stream().map(date -> (Double) date + 1).collect(Collectors.toList());

一对多映射flatMap

    //测试flatmap   1对多的写法  这儿相当于把一个对象集合分裂成对象的属性集合
    for (int i = 0; i < 10; i++) {
        aList.add(new A("name" + i, "age" + i));
    }
    List<String> cc=aList.stream().flatMap(a -> Arrays.stream(new String[]{a.getAge(),a.getName()})).collect(Collectors.toList());
    for (String s : cc) {
        System.out.print(s+"     ");
    }

age0 name0 age1 name1 age2 name2 age3 name3 age4 name4 age5 name5 age6 name6 age7 name7 age8 name8 age9 name9

map转换为map

Map<String, Integer> type = reportHeights.stream().collect(groupingBy(RptGGeoClass::getOutLevel)).entrySet().parallelStream()
        .collect(Collectors.toMap(entry -> {
            Object dicName = redisTemplate.opsForHash().get(RedisKeysMdc.getDicKey("SysDicMap"), String.valueOf(entry.getKey()));
            return Objects.isNull(dicName) ? "" : dicName.toString();
        }, entry -> entry.getValue().size()));

LocalDateTime、LocalDate和DateTimeFormatter

详见:https://blog.csdn.net/qq_27093465/article/details/78909797
//日期比较:两者相差多少天,第一个参数是start,第二个是end
LocalDate raiseDate = bizRaisedTime.toLocalDate();
LocalDate currentDate = LocalDate.now();
Period period = Period.between(raiseDate, currentDate);
int year = period.getYears();
int month = period.getMonths();
int day = period.getDays();
logger.info("{}和{}相差{}年{}月{}天!", raiseDate.toString(), currentDate.toString(), year, month, day);
if (year > 0 || month > 0 || day > expireDay) {
    logger.info("删除redis里面key={}的缓存!", key);
    redisService.del(key);
}

stream的map和peek区别

peek接收一个没有返回值的λ表达式,可以做一些输出,外部处理等。

map接收一个有返回值的λ表达式,之后Stream的泛型类型将转换为map参数λ表达式返回的类型

参见: https://blog.csdn.net/tckt75433/article/details/81510743

map改变key和value

   //统计超限数量
    Map<String, Integer> num = reportHeights.stream().collect(groupingBy(RptGGeoClass::getOutTypeName)).entrySet().stream()
            .collect(Collectors.toMap(Map.Entry::getKey, entry -> entry.getValue().size()));