Java Stream: Convert List<Object> to Map<String, Object>
<p>{"title":"Java Stream: Convert List<Object> to Map<String, Object>","description":"Learn how to efficiently transform a List of Objects into a Map in Java using the powerful Stream API. This guide provides a clear example and explanation, including handling duplicate keys and a practical use case.","keywords":"Java, Stream, List, Map, Object, Collectors.toMap, Conversion, Data Structures, Programming, Tutorial","content":"You can use Java 8's Stream API to convert a List<Object> to a Map<String, Object>. Here's an example code:\n\n<code>java\nimport java.util.List;\nimport java.util.Map;\nimport java.util.stream.Collectors;\n\npublic class Main {\n public static void main(String[] args) {\n List<Object> list = List.of(\n new Person("John", 25),\n new Person("Alice", 30),\n new Person("Bob", 35)\n );\n\n Map<String, Object> map = list.stream()\n .collect(Collectors.toMap(\n obj -> ((Person) obj).getName(),\n obj -> obj\n ));\n\n System.out.println(map);\n }\n}\n\nclass Person {\n private String name;\n private int age;\n\n public Person(String name, int age) {\n this.name = name;\n this.age = age;\n }\n\n public String getName() {\n return name;\n }\n\n public int getAge() {\n return age;\n }\n\n @Override\n public String toString() {\n return "Person{" +\n "name='" + name + "'" +\n ", age=" + age +\n '}';\n }\n}\n</code>\n\nOutput:\n\n<code>\n{John=Person{name='John', age=25}, Alice=Person{name='Alice', age=30}, Bob=Person{name='Bob', age=35}}\n</code>\n\nIn this example, we use the <code>stream()</code> method to convert the List to a Stream, then use the <code>Collectors.toMap()</code> method to convert the Stream elements to a Map. The first argument of the <code>toMap()</code> method is the key extractor function, where we use the <code>getName()</code> method to extract the name of each Person object as the key. The second argument is the value extractor function, where we use the object itself as the value.\n\nNote that if there are duplicate keys (names in this case) in the list, an <code>IllegalStateException</code> will be thrown. You can handle duplicate keys by using a third argument, for example, using <code>Collectors::merge</code> to merge the values.\n\n</p>
原文地址: https://www.cveoy.top/t/topic/p8md 著作权归作者所有。请勿转载和采集!