Generic static method constrains types too much

后端 未结 3 1677
北海茫月
北海茫月 2021-01-25 05:28

In this answer I attempted to create a static utility method to make a List into a Map:

public static  Map toMa         


        
3条回答
  •  无人及你
    2021-01-25 06:17

    With this bit:

    Map peopleById1 = students.stream()
            .collect(Collectors.toMap(Student::getId, Function.identity()));
    

    Notice that you do not provide arguments to Function.identity(). The compiler is free to infer it as Function.identity() to resolve the difference imposed by the return value assignment.

    This should be good enough for your purpose:

    public static  Map toMapBy(
        List list, // <- note
        Function mapper
    ) {
        ...
    }
    

    Now the elements of the List can be a subtype of the Map values. Or you can define a third parameter like @Alex has suggested.

提交回复
热议问题