簡體   English   中英

Java8:在Collectors.toMap(..)中使用Function :: identity會產生參數不匹配錯誤

[英]Java8: Using Function::identity in Collectors.toMap(..) creates an argument mismatch error

鑒於這個簡單的人POJO:

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;
    }
}

我想收集一個Map<String, Person> ,其中key是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());
    }
}

但我得到一個編譯錯誤:

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))

作為一個解決方案,我可以用這個lambda p -> p替換Function::identity ,如下所示:

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

是否有可能使用Function::identity

您不應該使用方法參考。 你應該使用Function.identity()

如果使用方法引用,則基本上是嘗試傳遞Supplier<Function<T, T>>

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM