• 周二. 5月 7th, 2024

5G编程聚合网

5G时代下一个聚合的编程学习网

热门标签

使用Stream 流将集合对象指定属性转换成 Map 集合

admin

11月 28, 2021

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
坚持做好每件事,然后再做下一件。

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注