Где mappedRoles = Maps.uniqueIndex
... можно увидеть, что Netbeans производит следующую ошибку:
no suitable method found for uniqueIndex(List<ReducedEntity>,<anonymous java.util.function.Function<ReducedEntity,Integer>>)
method Maps.<K#1,V#1>uniqueIndex(Iterable<V#1>,com.google.common.base.Function<? super V#1,K#1>) is not applicable
(cannot infer type-variable(s) K#1,V#1
(argument mismatch; <anonymous java.util.function.Function<ReducedEntity,Integer>> cannot be converted to com.google.common.base.Function<? super V#1,K#1>...
Демо-версия:
package com.mycompany.testground;
import com.google.common.collect.Maps;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
public class Main {
public static void main(String[] args) {
List<ReducedEntity> list = new ArrayList<>();
Map<Integer, ReducedEntity> mappedRoles;
mappedRoles = Maps.uniqueIndex(list, new Function<ReducedEntity, Integer>() {
@Override
public Integer apply(ReducedEntity from) {
return from.getId();
}
});
}
}
Уменьшенный класс сущностей для полноты (но, вероятно, не нужен)
package com.mycompany.testground;
public class ReducedEntity {
protected Integer id;
protected String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Создал выше, после того, как Jons ответил на эту страницу. Java: как преобразовать List <?> В Map <String,?>, И я еще не могу понять, почему это не работает, как показано.
Вы используете java.util.function.Function
. Метод Maps.uniqueIndex()
ожидает функцию com.google.common.base.Function
. Исправьте свой импорт.
java.util.function.Function
, вы компилируете с JDK8. В каком случае вы можете использовать функции Java 8? Если вы замените целуюFunction
ссылкой на метод, такой какReducedEntity::getId
, вам даже не придется беспокоиться о том, какой типFunction
принимает метод.