Java 8: 将 List<V4Customer> 转为 Map (字段作为键, 对象作为值)
您可以使用 Java 8 的流式操作和 Collectors 的 toMap 方法将 List
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 中的键值对。
原文地址: https://www.cveoy.top/t/topic/qFhK 著作权归作者所有。请勿转载和采集!