您可以使用Java 8的流式操作和Collectors的toMap方法将List转换为Map,其中一个字段作为key,整个对象作为value。以下是示例代码:

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

public class Main {
    public static void main(String[] args) {
        List<V4Customer> v4CustomerList = createV4CustomerList();

        // 使用Java 8流式操作和Collectors的toMap方法将List转换为Map
        Map<String, V4Customer> v4CustomerMap = v4CustomerList.stream()
                .collect(Collectors.toMap(V4Customer::getKeyField, v4Customer -> v4Customer));

        // 打印Map中的键值对
        v4CustomerMap.forEach((key, value) -> System.out.println(key + " : " + value));
    }

    private static List<V4Customer> createV4CustomerList() {
        List<V4Customer> v4CustomerList = List.of(
                new V4Customer("key1", "John"),
                new V4Customer("key2", "Jane"),
                new V4Customer("key3", "Mike")
        );
        return v4CustomerList;
    }

    static class V4Customer {
        private String keyField;
        private String name;

        public V4Customer(String keyField, String name) {
            this.keyField = keyField;
            this.name = name;
        }

        public String getKeyField() {
            return keyField;
        }

        public String getName() {
            return name;
        }

        @Override
        public String toString() {
            return "V4Customer{" +
                    "keyField='" + keyField + '\'' +
                    ", name='" + name + '\'' +
                    '}';
        }
    }
}

在上面的示例代码中,我们创建了一个V4Customer类,并在createV4CustomerList方法中初始化一个V4Customer列表。然后,我们使用流式操作和Collectors的toMap方法将List转换为Map。在toMap方法中,使用V4Customer的getKeyField方法作为key,整个V4Customer对象作为value。最后,我们使用forEach方法打印Map中的键值对

ListV4Customer v4CustomerList 用java8 转为map其中一个字段作为key整个对象作为value

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

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