Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

More optimal solution?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading