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

 


版权声明:本文为X_kai_style原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。