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

Sort list in ascending last name length by implementing the comparator interface through an anonymous class

This is from the task:

Select Comparator<> as the implemented interface.
Inside the anonymous class, override the comparison method, namely compare.
To get the last name from a string, split the string on a space using split and take the second part of the split.

import java.util.stream.Collectors;

public class Practicum {
    public static void main(String[] args) throws Exception {
        List<String> people = new ArrayList<>(List.of(
                "Maria Zue",
                "Anna Darkness",
                "Kirl Filimon",
                "Eva Pink"
        ));

        Comparator<String> comparator = ... // <-- write your code here
        };

        Collections.sort(people, comparator);

        System.out.println(people);
    }
}


// My desicion wasn't correct:
Comparator<String> comparator = new Comparator<>() { // <-- write your code here
@Override
public int compare(String o1, String o2) {
    return o1.split(" ")[1].compareTo(o2.split(" ")[1]);
    }
};

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 :

You are on the right path, you just need to compare the length of the strings and not the strings themselves:

Comparator<String> comparator = new Comparator<>() {
    @Override
    public int compare(final String o1, final String o2) {
        return Integer.compare(o1.split(" ")[1].length(), o2.split(" ")[1].length());
    }
};

Using lambda expression you can simplify the above aand rewrite it as:

Comparator<String> comparator = (o1, o2) -> Integer.compare(o1.split(" ")[1].length(), o2.split(" ")[1].length());

the above can get further refactored using Comparator.comparingInt

Comparator<String> comparator = Comparator.comparingInt(o -> o.split(" ")[1].length());
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