list对象转map

在使用 java.util.stream.Collectors 类的 toMap() 方法转为 Map 集合时,一定要使用参数类型 为 BinaryOperator,参数名为 mergeFunction 的方法,否则当出现相同 key 时会抛出 IllegalStateException 异常。

说明:参数 mergeFunction 的作用是当出现 key 重复时,自定义对 value 的处理策略。

正例:

1
2
3
4
5
6
7
8
List<Pair<String, Double>> pairArrayList = new ArrayList<>(3);
pairArrayList.add(new Pair<>("version", 12.10));
pairArrayList.add(new Pair<>("version", 12.19));
pairArrayList.add(new Pair<>("version", 6.28));
// 生成的 map 集合中只有一个键值对:{version=6.28}
Map<String, Double> map = pairArrayList.stream()
        .collect(Collectors.toMap(Pair::getKey, Pair::getValue, (v1, v2) -> v2));
System.out.println(map);//{version=6.28}

反例:

1
2
3
4
5
6
7
8
9
String[] departments = new String[]{"aaa", "aaa", "bbb"};
// 抛出 IllegalStateException 异常
Map<Integer, String> map = Arrays.stream(departments)
        .collect(Collectors.toMap(String::hashCode, str -> str));
System.out.println(map);
 
Map<Integer, String> map2 = Arrays.stream(departments)
        .collect(Collectors.toMap(String::hashCode, str -> str, (v1, v2) -> v2));
System.out.println(map2);//{96321=aaa, 97314=bbb}

  

在使用 java.util.stream.Collectors 类的 toMap() 方法转为 Map 集合时,一定要注意当 value 为 null 时会抛 NPE 异常。

说明:在 java.util.HashMap 的 merge 方法里会进行如下的判断:

1
2
if (value == null || remappingFunction == null)
    throw new NullPointerException();

反例:

1
2
3
4
5
6
7
List<Pair<String, Double>> pairArrayList = new ArrayList<>(2);
pairArrayList.add(new Pair<>("version", 12.10));
pairArrayList.add(new Pair<>("version", null));
// 抛出 NullPointerException 异常
Map<String, Double> map = pairArrayList.stream()
        .collect(Collectors.toMap(Pair::getKey, Pair::getValue, (v1, v2) -> v2));
System.out.println(map);

  

附:

1
2
3
4
5
6
7
8
9
10
11
12
13
@Data
public class Pair<T,P> {
 
    public Pair(T key, P value) {
        this.key = key;
        this.value = value;
    }
 
    T key;
 
    P value;
 
}

 

来源: Java开发手册1.7.1 - (六) 集合处理 - 3

posted @   草木物语  阅读(1082)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示