Stream使用Collector.tomap方法value值为null时报空指针异常 解决方案

import junit.framework.TestCase;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Optional;
import java.util.stream.Collectors;

public class TestCollect extends TestCase {
    class User {
        String userName;
        String sex;
        String idCard;

        //省略Getter and Setter  and Constructor方法
    }

    /**
     * @param
     * @description: 取出集合中User对象的userName和idCard属性取出放在map中
     * @return: void
     * @author: Sue
     * @date: 2020/8/14
     */
    public void testCollect() {
        User user01 = new User("user01", "male", "000000001");
        User user02 = new User("user02", "male", "000000002");
        User user03 = new User("user03", "male", "000000003");
        User user04 = new User(null, "male", "000000004");
        User user05 = new User("user05", "male", null);
        ArrayList<User> list = new ArrayList();
        list.add(user01);
        list.add(user02);
        list.add(user03);
        list.add(user04);
        list.add(user05);

        /**
         * 当存在value值为空时,使用Collectors.toMap()会报NPE
         * 原因:底层调用了Map的merge方法,而map方法规定了此处的vlue不能为null,从而抛出空指针异常
         * Objects.requireNonNull(value);
         */
//        HashMap<String, String> map01 = list.stream().collect(Collectors.toMap(User::getUserName, User::getIdCard, (a, b) -> b, HashMap::new));
//        System.out.println(map01);

        //解决方案一,使用Optional类处理null
        HashMap<String, String> map02 = list.stream().collect(Collectors
                .toMap(s -> Optional.ofNullable(s.getUserName()).orElse("空的"), s -> Optional.ofNullable(s.getSex()).orElse("空的"), (a, b) -> b, HashMap::new));
        System.out.println(map02);

        //解决方案二,直接使用collect()方法进行规约操作,关于这里collect方法的使用可以看这篇文章 https://www.cnblogs.com/sueyyyy/p/13502116.html
        HashMap<String, String> map03 = list.stream().collect(HashMap::new, (map, item) -> map.put(item.getUserName(), item.getSex()), HashMap::putAll);
        System.out.println(map03);
    }
}
  
  

  

posted @ 2020-08-14 14:33  少说点话  阅读(1044)  评论(0编辑  收藏
网站运行: