zoukankan      html  css  js  c++  java
  • 使用Stream 流将集合对象指定属性转换成 Map 集合

    1. 创建容器对象 Person 类

    
    import lombok.Data;
    
    
    @Data
    public class Person {
        
        public Person(Long id,String name, Boolean gender, Integer age, float score) {
            this.id = id;
            this.name = name;
            this.gender = gender;
            this.age = age;
            this.score = score;
        }
        public Person(String name, Boolean gender) {
            this.name = name;
            this.gender = gender;
        }
    
        private Long id;
        private String name;
        private Boolean gender;
        private Integer age;
        private float score;
    
    }
    

    2. 在测试方法中实现功能

    
    import java.util.Arrays;
    import java.util.List;
    import java.util.Map;
    import java.util.stream.Collectors;
    
    public class StreamMainTest {
        public static void main(String[] args) {
            // 创建包含 id 的对象
            Person p1 = new Person(1L, "zhangsan", false, 19, 60);
            Person p2 = new Person(2L, "lisi", true, 20, 80);
            Person p3 = new Person(3L, "wangmazi", false, 28, 70);
            Person p4 = new Person(4L, "meiyoule", true, 15, 50);
            // 创建不包含 id 的对象
            Person p5 = new Person("evsd", true);
            Person p6 = new Person("evsd", true);
            // 将对象装入 list 集合中
            List<Person> people = Arrays.asList(p1, p2, p3, p4, p5, p6);
    
            Map<Long, String> idAndNameMap = people.stream()
                    // 过滤掉 id 为空的对象
                    .filter(person -> (null != person.getId()))
                    // 将对象的 id 和 name 取出转换成 map 集合
                    .collect(Collectors.toMap(Person::getId, Person::getName));
            // 处理map 中 value 中有 null 的情况
            Map<Long, String> idAndNameMapHasNull = people.stream().collect(HashMap::new,
                    (m, v)->m.put(v.getId(), v.getName()), HashMap::putAll);
            // 遍历输出 map 集合
            idAndNameMap.forEach((key, value) -> {
                  System.out.println(key + "--- " + value);
            });
        }
    }
    
    
    

    输出效果

    1--- zhangsan
    2--- lisi
    3--- wangmazi
    4--- meiyoule
    
    Process finished with exit code 0
    
    坚持做好每件事,然后再做下一件。
  • 相关阅读:
    JS 知识点补充
    JS 数据之间类型的转化
    JS 数据的类型
    数据结构--数组、单链表和双链表介绍 以及 双向链表
    数据结构--队列
    数据结构--栈
    24. 两两交换链表中的节点
    23. 合并K个排序链表
    22. 括号生成
    21. 合并两个有序链表
  • 原文地址:https://www.cnblogs.com/vawa/p/15079465.html
Copyright © 2011-2022 走看看