Question:
The input is a text string. The word with the highest sum of character code values must be returned. Sorting must be done in the opposite direction. I use the reversed()
method, but then I cannot use the chars()
method, since w
type Object
. What is the correct way to sort in reverse order?
public static String high(String s) {
return Stream.of(s.split(" "))
.sorted(Comparator.comparingInt(w -> w.chars().sum()).reversed())
.toArray(String[]::new)[0];
}
Answer:
Try this:
public static String high(String s) {
return Stream.of(s.split(" "))
.sorted(Comparator.comparing(String::chars, Comparator.comparingInt(IntStream::sum)).reversed())
.toArray(String[]::new)[0];
}
This method takes a key extractor as its first argument, i.e. what data we need to pull out for sorting, and the second argument takes HOW we will sort. Well, that is, everything is simple, we pulled out the IntStream
charms and sorted them by their sum