Java8 对list集合的处理

1.list转map(List 转 Map)

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

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

 Map> 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 

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

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

5.筛选list

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

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

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

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


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

7.list中提取属性,并收集为一个新的集合

List userList = new ArrayList<>();
public class User {
    private int userId;
    private String userName;
}
//提取userList中的userId属性作为新的集合
List userIdList = userList.stream.map(x -> x.getUserId()).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

 

你可能感兴趣的:(Java)