Reputation: 33
I am getting type cast error when trying to collect the list of objects to Map using lambda expression java 8
here is the code:
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))
);
}
once I type cast it to (Player) like below, it works fine. any idea why compiler asking for type cast?
player -> ((Player) player).getName()+"_"+((Player) player).getAge()
Player class is as below:
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
}
Upvotes: 3
Views: 1073
Reputation: 15714
This has been an issue in certain versions (I want to say 1.8.0_45, but I can't confirm). I just tried your code on 1.8.0_71 and it works for me.
The latest version is 1.8.0_111, so you should try upgrading to that.
Upvotes: 2