Java8:在Collectors.toMap(..)中使用Function :: identity会产生参数不匹配错误

时间:2018-05-24 08:31:04

标签: java generics java-stream collectors

鉴于这个简单的人POJO:

>>> re.match(r'\s+(High)\s+(\d+\:\d+)(AM|PM)\s+(\d+\.\d+)m', s).groups()
('High', '4:55', 'AM', '1.3')

我想收集一个public class Person { private String id; private String name; public Person(String id, String name) { super(); this.id = id; this.name = name; } public String getId() { return id; } public String getName() { return name; } } ,其中密钥是Person的Map<String, Person>

我试图像这样实现它:

id

但是我收到编译错误:

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class CollectorMain {
    public static void main(String[] args) {
        List<Person> list = new ArrayList<>();
        list.add(new Person("312", "John"));
        list.add(new Person("454", "Alice"));
        list.add(new Person("712", "Bob"));

        Map<String, Person> map = list.stream()
               .collect(
                    Collectors.toMap(Person::getId, Function::identity) // COMPILE ERROR
               );
        System.out.println(map.size());
    }
}

作为一种解决方案,我可以用这样的lambda CollectorMain.java:[14,41] no suitable method found for toMap(Person::getId,Function::identity) method java.util.stream.Collectors.<T,K,U>toMap(java.util.function.Function<? super T,? extends K>,java.util.function.Function<? super T,? extends U>) is not applicable (cannot infer type-variable(s) T,K,U (argument mismatch; incompatible parameter types in method reference)) method java.util.stream.Collectors.<T,K,U>toMap(java.util.function.Function<? super T,? extends K>,java.util.function.Function<? super T,? extends U>,java.util.function.BinaryOperator<U>) is not applicable (cannot infer type-variable(s) T,K,U (actual and formal argument lists differ in length)) method java.util.stream.Collectors.<T,K,U,M>toMap(java.util.function.Function<? super T,? extends K>,java.util.function.Function<? super T,? extends U>,java.util.function.BinaryOperator<U>,java.util.function.Supplier<M>) is not applicable (cannot infer type-variable(s) T,K,U,M (actual and formal argument lists differ in length)) 代替Function::identity

p -> p

是否有可能使用Map<String, Person> map = list.stream() .collect( Collectors.toMap(Person::getId, p -> p) );

1 个答案:

答案 0 :(得分:7)

您不应该使用方法参考。您应该使用Function.identity()

如果您使用方法参考,那么您基本上是尝试传递Supplier<Function<T, T>>

Map<String, Person> map = list.stream().collect(
    Collectors.toMap(Person::getId, Function.identity())
);