Advertisements
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]);
}
};
>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());