【JDK1.8新特性】集合stream()常见用法介绍

集合转map(key唯一)

List<Entity> entitys;
Map<String, Entity> entityMaps = entitys.stream().collect(Collectors.toMap(e -> "" + e.getId(), e -> e, (entity1, entity2) -> entity1));

集合转map,取某一字段作为value(key唯一)

List<Entity> entitys;
Map<String, Integer> sIMap = entitys.stream().collect(Collectors.toMap(Entity::getId, Entity::getTotalCount, (entity1, entity2) -> entity1));

集合转map,分组统计

List<Entity> entitys;
Map<String, Long> map = entitys.stream().collect(Collectors.groupingBy(Entity::getId, Collectors.counting()));

集合过滤filter

List<Entity> entitys;
entitys = entitys.stream().filter(s -> Constant.id.equals(s.getId())).collect(Collectors.toList());

集合分组groupingBy

List<Entity> entitys;
Map<String, List<Entity>> entitysMap = entitys.stream().collect(Collectors.groupingBy(Entity::getId));

Map<String, List<Entity>> entitysMap = entitys.stream().collect(Collectors.groupingBy(i -> i.getA() + "_" + i.getB()));


Map<String, List<Entity>> entitysMap = entitys.stream().collect(Collectors.groupingBy(
    i -> {
    if(i.getA() < 3) {
        return "3";
    }else {
        return "other";
    }
}
));

多级集合分组

Map<String, Map<String, List<Entity>>> entitysMap = entitys.stream().collect(Collectors.groupingBy(Entity::getId, Collectors.groupingBy(i -> {
    if(i.getA() < 3) {
        return "3";
    }else {
        return "other";
    }
})));

集合取某一字段重组集合

List<Entity> entitys;
List<Long> ids = entitys.stream().flatMap(Collection::stream)
        .map(Entity::getId).collect(Collectors.toList());
List<Long> ids = entitys.stream().map(s -> s.getId()).collect(Collectors.toList());

List根据某个字段求和

int sum = entitys.stream().collect(Collectors.summingInt(Entity::getNumber));

int ageSum = entitys.stream().mapToInt().sum(Entity::getNumber);

集合根据某一字段排序

List<Entity> entitys;
entitys = entitys.stream().sorted(Comparator.comparing(entitys::getId)).collect(Collectors.toList());

 集合-Map根据排序

 List<Entity> entitys;
entitys = entitys.stream().sorted(Comparator.comparing((Map m) -> (new BigDecimal(m.get("age").toString())))).collect(Collectors.toList());

List 转字符串

第一种:使用谷歌Joiner方法
String result = Joiner.on(",").join(list);

第二种:stream流
String result = list.stream().map(String::valueOf).collect(Collectors.joining(","));

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值