You can use streams to convert a List<Object> to a Map<String, Object> and handle duplicate keys using the overloaded versions of the toMap method. Here's an example code:

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

public class Main {
    public static void main(String[] args) {
        List<Object> list = List.of(
                new Person('John', 25),
                new Person('Jane', 30),
                new Person('John', 35)
        );

        Map<String, Object> map = list.stream()
                .collect(Collectors.toMap(
                        obj -> ((Person) obj).getName(),
                        obj -> obj,
                        (existing, duplicate) -> duplicate,
                        HashMap::new
                ));

        System.out.println(map);
    }
}

class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    @Override
    public String toString() {
        return 'Person{' +
                'name=' + name + ''' +
                ', age=' + age +
                '}';
    }
}

Output:

{John=Person{name='John', age=25}, Jane=Person{name='Jane', age=30}}

In the toMap method, we use the following parameters:

  • keyMapper: This function maps the object to a key. Here, we use the name property of the Person object as the key.
  • valueMapper: This function maps the object to its corresponding value. In this case, we simply use the object itself as the value.
  • mergeFunction: This function is used to handle duplicate keys. We directly use the duplicate object as the value in this example.
  • mapSupplier: This specifies the type of Map to be generated. We use HashMap in this case.

This code demonstrates how to effectively convert a List to a Map while handling potential duplicate keys using streams. By understanding the toMap method and its parameters, you can efficiently manage and manipulate your data in Java.

Java List to Map Conversion with Duplicate Keys Handling using Streams

原文地址: https://www.cveoy.top/t/topic/quqw 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录