Search code examples
javajava-streamjava-17

How to get list element with minimal property?


I write this code to find the youngest person:

import java.util.Comparator;
import java.util.List;

public class PersonImpl implements PersonInterface {

    @Override
    public Person youngest(List<Person> personList) {
        Integer minAge = personList.stream()
                .map(Person::getAge)
                .min(Comparator.comparing(Integer::valueOf))
                .orElse(null);
        return personList.stream()
                .filter(person -> person.getAge() == minAge)
                .toList()
                .stream()
                .findFirst()
                .orElse(null);
    }
}

As you can see I did it and is working correctly . Now I want to know if I can do this in a better way (maybe instead of having 2 "statements" to go done to only one?) PS: I provided only the code since I assume that there is no need to post all the other classes in here just to review this one only.

Can someone explain me what can be done to have a better code(less lines)? Thanks


Solution

  • Just cut out the map() and have your comparator do the age lookup on Person:

    return personList.stream()
            .min(Comparator.comparingInt(Person::getAge))
            .orElse(null);
    

    If you know the list is non-empty, better to make that explicit by calling get() or orElseThrow() instead of orElse(). Or you can use the Collections helper instead of streams:

    return Collections.min(personList, Comparator.comparingInt(Person::getAge));
    

    By the way, calling .toList().stream() when you already have a stream is completely pointless. There's also no point in calling Integer::valueOf on an Integer.