List<Map<String,String>>使用Stream流转化为Map<String,List<String>>

按不同的key进行分组,将相同key的value存储到list中

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class productSKU {
    
    
    public static void main(String[] args) {
    
    
        HashMap<String, String> map1 = new HashMap<>();
        HashMap<String, String> map2 = new HashMap<>();
        HashMap<String, String> map3 = new HashMap<>();
        map1.put("productid", "123");
        map1.put("id", "111");
        map2.put("productid", "123");
        map2.put("id", "1234");
        map3.put("productid", "222");
        map3.put("id", "333");
        List<Map<String, String>> list = new ArrayList<>();
        list.add(map1);
        list.add(map2);
        list.add(map3);
        Map<String, List<String>> collect = list.stream().collect(Collectors.groupingBy(map ->
                map.get("productid").toString(), Collectors.mapping(map -> map.get("id").toString(), Collectors.toList())));
        System.out.println(collect);
        //输出{222=[333], 123=[111, 1234]}
    }
}

原文链接:https://blog.csdn.net/weixin_43842753/article/details/119618902

猜你喜欢

转载自blog.csdn.net/u010741112/article/details/129959309
今日推荐