java 8 Stream list to Map key duplicate value is merged into Collection

There are many blogs about the map that converts a list into a key value. Here is one that puts the value into the collection.

 

      List<String> list = Lists.newArrayList("1", "2", "3", "1");
        Map<String, List<String>> map = list.stream().collect(Collectors.toMap(key -> key,
                value -> Lists.newArrayList(value),
                (List<String> newValueList, List<String> oldValueList) -> {
                    oldValueList.addAll(newValueList);
                    return oldValueList;
                }));
        System.out.println(JSON.toJSONString(map));

 Similarly, your list generic can be a bean, take the properties of the bean as key or value, and convert it into a collection

 

结果: {"1":["1","1"],"2":["2"],"3":["3"]}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327060398&siteId=291194637