[英]Create a Map<Key,Object> based on a List<Object> - Converting Loops into Java streams
Facing error while converting a List<Object>
to a HashMap<Key,Object>
.将List<Object>
转换为HashMap<Key,Object>
时遇到错误。
I can do with a traditional code, but I'm getting an error while doing using Java 8 streams and ignore the duplicate keys.我可以使用传统代码,但是在使用 Java 8 流并忽略重复键时出现错误。
Equivalent code:等效代码:
Map<String, Field> uniqueFields = new HashMap<>();
for (Field field : allFields) {
uniqueFields.put(field.getName(), field);
}
Tried below stream, but there's a syntactic mistake:在下面的流中尝试过,但是有一个语法错误:
Map<String, Field> uniqueFields1 = allFields.stream()
.collect(Collectors.toMap(
Field::getName,
(oldValue, newValue) -> oldValue));
You just need one more argument to the toMap
function to tell the collector what should be the values of the Map
.您只需toMap
函数添加一个参数来告诉收集器Map
的值应该是什么。 You can use Function.identity()
, which means it will just pass the Field
right through.您可以使用Function.identity()
,这意味着它只会直接通过Field
。
Map<String,Field> uniqueFields = allFields.stream()
.collect(Collectors.toMap(Field::getName, Function.identity(),
(oldValue,newValue) -> oldValue));
The flavor of Collectors.toMap()
, that expects two arguments, should be provided with Function
s: keyMapper and valueMapper (that are responsible for expracting a key and a value respectivelly from a stream element).需要两个参数的Collectors.toMap()
的风格应该由Function
s 提供: keyMapper和valueMapper (它们分别负责从流元素中提取键和值)。
But in your code snippet, the second argument isn't of type Function
, because you've provided two arguments oldValue, newValue
, but Function
takes only one.但是在您的代码片段中,第二个参数不是Function
类型,因为您提供了两个参数oldValue, newValue
,但Function
只接受一个。
You need to use a version of toMap
that in addition to keyMapper and valueMapper functions expects the third argument BinaryOperator
mergeFunction which is meant to resolve values mapped to the same key :您需要使用toMap
的一个版本,除了keyMapper和valueMapper函数之外,还需要第三个参数BinaryOperator
mergeFunction ,它旨在解析映射到同一键的值:
Map<String, Field> uniqueFields = allFields.stream()
.collect(Collectors.toMap(
Field::getName, // generating a kay
Function.identity(), // generating a value
(oldValue, newValue) -> oldValue))); // resolving duplicates
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.