List v4CustomerList 用java8 转为map其中一个字段作为key整个对象作为value
可以使用Java 8的流(Stream)和Collectors工具类来将List转换为Map。
假设v4CustomerList是一个List
Map<KeyType, V4Customer> customerMap = v4CustomerList.stream()
.collect(Collectors.toMap(V4Customer::getKeyField, Function.identity()));
其中KeyType是作为key的字段的类型,V4Customer::getKeyField表示获取V4Customer对象的key字段,Function.identity()表示将整个V4Customer对象作为value。
注意,如果v4CustomerList中存在重复的key字段值,上述代码会抛出一个IllegalStateException异常。如果你希望在遇到重复key时进行处理,可以使用第三个参数来指定如何解决冲突,例如:
Map<KeyType, V4Customer> customerMap = v4CustomerList.stream()
.collect(Collectors.toMap(V4Customer::getKeyField, Function.identity(), (existing, replacement) -> existing));
上述代码中,(existing, replacement) -> existing表示当遇到重复key时保留已存在的value。你也可以根据需要自定义解决冲突的逻辑
原文地址: https://www.cveoy.top/t/topic/iZgI 著作权归作者所有。请勿转载和采集!