This code results in the error “Non-static method cannot be referenced from a static context”:
public static Optional<String> getAuthorWithMostPublishedBooks(){
return books.stream()
.collect(Collectors.groupingBy(Book::getAuthor, Collectors.counting()))
.entrySet().stream()
.max(Comparator.comparing(Map.Entry::getValue).thenComparing(Comparator.comparing(Map.Entry::getKey).reversed()))
.map(Map.Entry::getKey);
}
This version compiles successfully:
public static Optional<String> getAuthorWithMostPublishedBooks(){
return books.stream()
.collect(Collectors.groupingBy(Book::getAuthor, Collectors.counting()))
.entrySet().stream()
.max(Comparator.comparing(Map.Entry<String, Long>::getValue).thenComparing(Comparator.comparing(Map.Entry<String, Long>::getKey).reversed()))
.map(Map.Entry::getKey);
}
Is the issue due to different types of the Comparator’s keys?
The method should return the author with the most published books in the list. If there’s a tie, the first author in alphabetical order must be selected