尝试使用lambda表达式java 8
收集Map的对象列表时,我遇到了类型转换错误这是代码:
public static void main(String[] args){
List<Player> players = Arrays.asList(
new Player("Liz", Gender.FEMALE, 20),
new Player("Liz", Gender.FEMALE, 22),
new Player("Bob", Gender.MALE, 20)
);
System.out.println(
players.stream()
.collect(toMap(
player -> player.getName()+"_"+player.getAge(),
// above line giving error.
//The method getAge() is undefined for the type Object
//- The method getName() is undefined for the type Object
player -> player))
);
}
一旦我将其类型转换为(播放器),如下所示,它可以正常工作。任何想法为什么编译器要求类型转换?
player -> ((Player) player).getName()+"_"+((Player) player).getAge()
玩家类如下:
class Player {
private String name;
private Integer age;
private Gender gender;
public Player(String name, Gender gender, Integer age){
this.name = name;
this.gender = gender;
this.age = age;
}
// ...... with corresponding getters and setters
}
答案 0 :(得分:2)
这在某些版本中是一个问题(我想说1.8.0_45,但我无法确认)。我刚刚在1.8.0_71上尝试了你的代码,它对我有用。
最新版本是1.8.0_111,所以你应该尝试升级到它。