我有一个类MyObject,例如:
class MyObject{
String name;
String age;
String address;
String cardNo;
}
我有一个List
我已经尝试过这样的事情,
myObjList.stream().collect(
Collectors.toMap(
MyObject::getName,
MyObject::getAge,
(k, v) -> HashMap::new
)));
您可以尝试以下方法:
myObjList.stream().collect(
Collectors.toMap(
MyObject::getName,
MyObject::getAge
)));
Collectors.toMap
已经包含HashMap::new
,因此不需要显式指定,如(来自Collectors.java
类)
public static <T, K, U> Collector<T, ?, Map<K,U>> toMap(Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends U> valueMapper) { return new CollectorImpl<>(HashMap::new, uniqKeysMapAccumulator(keyMapper, valueMapper), uniqKeysMapMerger(), CH_ID); }
但是,如果指定了第三个变量,则它应该是 Merge 函数,如下所示:
public static <T, K, U> Collector<T, ?, Map<K,U>> toMap(Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends U> valueMapper, BinaryOperator<U> mergeFunction) { return toMap(keyMapper, valueMapper, mergeFunction, HashMap::new); }
HashMap::new
也不需要在这里指定。
希望这有帮助。