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.

  • 2
    Only it is not clear why sorting, if then it falls into the map - Stranger in the Q
  • @Stranger you are right, it has now dawned on me that I did not correctly understand the essence of the task. Only one Person object should be in the map, which will have the largest age. - Artem

1 answer 1

First, the Person class needs getters.

 class Person { private String name; private int age; public Person (String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } } 

Second, the sorted method needs a comparator that will compare elements

 Map<String, Person> map = personList.stream() .sorted(Comparator.comparingInt(Person::getAge)) .collect(Collectors.toMap(Person::getName, Function.identity())); 

And in order to guarantee the preservation of the ordering of elements in the resulting collection, you should explicitly indicate its implementation:

 .collect(Collectors.toMap(Person::getName, Function.identity(), (a, b) -> a, LinkedHashMap::new)); 

UPD: To collect in the Map one element with the greatest age

 Map<String, Person> map = personList.stream() .sorted(Comparator.comparingInt(Person::getAge).reversed()) .limit(1) .collect(Collectors.toMap(Person::getName, Function.identity())); 

But then it is not clear why we need a Map for one element. You can just

 Person person = personList.stream() .max(Comparator.comparingInt(Person::getAge)) .get(); 
  • Thank you very much, only I confused you a little. It dawned on me that only one Person object should get into the map, which will have the largest age - Artem at 6:09 pm
  • one
    @Artem added the answer. - Sergey Gornostaev