Java8 对list集合的处理

1.list转map(List<User> 转 Map<user.getUid,user>)

Map<Integer, User> userMap = userList.stream().collect(Collectors.toMap(User::getUid,Function.identity()));

2.list转map并且分组(根据list中的对象的一个属性分组,类似于sql的groupby)

 Map<Integer, List<User>> usermap = userList.stream().collect(Collectors.groupingBy(User::getUid));

3.对集合中的每一个元素进行修改(如果元素为对象,也可以修改对象的属性)

下面代码中lambda表达式中x代表着userList中的元素对象也就是User对象(参数) -> 右边的表示方法体

userList.forEach(x -> x.setUsername("迭代遍历"+user.getUsername()));

4.map转list

userMap 是 Map<Integer,User> 

//将userMap的值(value)拿出来组成集合
List<User> collect = userMap.values().stream().collect(Collectors.toList());

//将userMap的键(key)拿出来组成集合
List<Integer> keyList = userMap.keySet().stream().collect(Collectors.toList());

5.筛选list

filter函数的()里,应该放逻辑,判断条件,将符合条件的放到resultList中

 List<User> resultList = userList.stream().filter(user -> user.getUid() == 2).collect(Collectors.toList());

6.list去重复(根据User对象的uid属性去重)

        List<User> oneList = getUserList(3);
        List<User> twoList = getUserList(3);
        oneList.addAll(twoList);
        System.out.println("去重前:"+oneList);
        List<User> distinctList = oneList.stream().filter(distinctByKey(o -> o.getUid())).collect(Collectors.toList());
        System.out.println("去重后:"+distinctList);


public static <T> Predicate<T> distinctByKey(Function<? super T,Object> keyExtractor){
        Map<Object,Boolean> been = new ConcurrentHashMap<>();
        //putIfAbsent()方法是如果key不存在则put如map中,并返回null
        //若key存在,则直接返回key所对应的value值
        return t -> been.putIfAbsent(keyExtractor.apply(t),Boolean.TRUE) == null;
    }

7.list中提取属性,并过滤掉属性为空的字段,并收集为一个新的集合

List<User> userList = new ArrayList<>();
public class User {
    private int userId;
    private String userName;
}
//提取userList中的userId属性作为新的集合
List<Integer> userIdList = userList.stream.map(x -> x.getUserId()).filter(x -> x != null).collect(Collectors.toList());

8.list对象属性的单列求和

int totalValue = goodsList.stream().mapToInt(Goods::getAmunt).sum();
        Goods good = new Goods();
        good.setAmunt(1);
        Goods good2 = new Goods();
        good2.setAmunt(3);
        Goods good3 = new Goods();
        good3.setAmunt(5);
totalValue = 9

 

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值