美文网首页
【JAVA基础】Lambda-集合类处理

【JAVA基础】Lambda-集合类处理

作者: 嘻洋洋 | 来源:发表于2019-08-20 15:31 被阅读0次

    java8中的Stream对集合功能进行了增强,以往我们经常对集合对象进行处理,比较繁琐。Stream提供了对集合对象的各种非常便利的、高效的聚合操作,通过lambda表达式提供了一些方便list操作的方法。

    1. Stream的最核心的方法:collect

    collect是一个将管道流的结果集到一个值的结束操作,这个值可以是集合、映射,或者一个值对象等。
    其用法的核心就是使用Collectors工具类来实现,它是在为Collector服务,用于创建各种不同的Collector。Collectors的toMap方法用法如下:
    (1)list 转 map

    List<Person> list = new ArrayList();  
    list.add(new Person(1, "haha"));  
    list.add(new Person(2, "rere"));  
    list.add(new Person(3, "fefe"));  
    //获取映射的键和值的策略
    Map<Integer, Person> mapp = list.stream().collect(Collectors.toMap(Person::getId, Function.identity()));  
    System.out.println(mapp.get(1).getName());  
    //如何获取映射的键和值的策略
    Map<Integer, String> map = list.stream().collect(Collectors.toMap(Person::getId, Person::getName));  
    System.out.println(map); 
    

    如果key有冲突的时候的处理,在发生冲突的情况下,我们保留现有条目:

    Map<Integer, String> map = list.stream().collect(Collectors.toMap(Person::getId, Person::getName,(existing, replacement) -> existing));  
    

    (2)List 转 ConcurrentMap,treemap等
    默认情况下,tomap()方法将返回哈希映射,同时我也可以返回其它映射:

    return list.stream().collect(Collectors.toMap(Person::getId, Function.identity(),(o1, o2) -> o1, ConcurrentHashMap::new))); 
    
    return list.stream().collect(Collectors.toMap(Person::getId, Function.identity(),(o1, o2) -> o1, TreeMap::new))); 
    

    Collectors中的还有很多方法,如joining、toList、分组等,部分功能与Stream中的方法重合了,为了简化代码,完全不必采用Collectors实现,优先Stream方法。

    2.通过Stream的filter方法可以过滤某些条件

    //排除掉工号为201901的用户
    List<User> userCommonList = userList.stream().filter(a -> !a.getJobNumber().equals("201901")).collect(Collectors.toList());
    

    3.映射(map)

    把一个序列映射成另一个序列,映射规则由一个函数制定。

    result = list.stream().filter(i -> UN_LOGIN.equals(i.getRemark())).map(this::chg2CodeInfo).collect(Collectors.toList());
    //函数
    public CodeInfo chg2CodeInfo(TbCode tbCode)
    {
        CodeInfo codeInfo = new CodeInfo();
        codeInfo.setCodeVal(tbCode.getCodeVal());
        codeInfo.setCodeDesc(tbCode.getCodeDesc());
        codeInfo.setRemark(tbCode.getRemark());
        return codeInfo;
    }
    
    
    

    相关文章

      网友评论

          本文标题:【JAVA基础】Lambda-集合类处理

          本文链接:https://www.haomeiwen.com/subject/lohgrctx.html