Java Stream Collectors.toMap: Creating a Map<String, List<Object>>
<p>The `Collectors.toMap` method returns a `Map` object with a specified key type and value type. In this case, we want the key type to be `String` and the value type to be `List<Object>`. \n\nHere's an example of how to use `Collectors.toMap` to achieve this result:\n\n<code>java\nList<Object> list = new ArrayList<>();\n// populate the list\n\nMap<String, List<Object>> map = list.stream()\n .collect(Collectors.toMap(\n // key mapper\n obj -> \"someKey\", \n // value mapper\n obj -> {\n List<Object> valueList = new ArrayList<>();\n valueList.add(obj);\n return valueList;\n },\n // merge function\n (list1, list2) -> {\n list1.addAll(list2);\n return list1;\n }\n ));\n</code>\n\nIn this example, we are using a constant key ("someKey") for all objects in the list. The value mapper function creates a new `ArrayList` with the current object as its only element. The merge function is used to combine values with the same key in case of collisions (i.e., multiple objects with the same key). It appends the values to an existing list.\n\nNote that you would need to adjust the key and value mapping logic to your specific use case.</p>
原文地址: https://www.cveoy.top/t/topic/p8n5 著作权归作者所有。请勿转载和采集!