I try to collect with using the stream, falls ClassCastException. In general, there is a Person class:
public class Person{ private String name; private int age; public Person (String name, int ;){ this.name= name; this.age= age; }
I need to create a Map using stream, and the objects there should be sorted by age. I write:
Person person1 = new Person("b", 1); Person person2 = new Person("c", 2); Person person3 = new Person("a", 3); List<Person > personList = new ArrayList<>(); personList.add(person1); personList.add(person2); personList.add(person3); Map<String, Person> map = personList.stream() .sorted().collect(Collectors.toMap((o -> o.getName()), o -> o));
I have a ClassCastException. I can not understand how the expression should look like a lambda inside toMap (). And another question is how to tell the sorted method to compare objects precisely by age, I did it only by name, I used compareTo (), but int is a primitive and here this option does not work.
I would be grateful for any help.