Doing the exercise 'Literature' on https://java-programming.mooc.fi/part-10/2-interface-comparable I discovered a very strange behavior when trying to sort key-value pairs in a HashMap, without copying anything to a TreeMap. I was supposed to add books, by making a Book class and adding them to a List. However I wanted to try without making a new class, so opted for the HashMap. My code was as follows:
public class MainProgram {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Map<String, Integer> bookshelf = new HashMap<>();
while (true) {
System.out.println("Input the name of the book, empty stops: ");
String bookName = scanner.nextLine();
if (bookName.equals("")) {
break;
}
System.out.println("Input the age recommendation: ");
int age = Integer.valueOf(scanner.nextLine());
bookshelf.put(bookName, age);
}
System.out.println(bookshelf.size() + " book" + (bookshelf.size() > 1 ? "s" : "") + " in total.");
System.out.println("Books:");
bookshelf.keySet().stream().sorted(Comparator.comparing(bookshelf::get)).forEach((key) -> System.out.println(key + " (recommended for " + bookshelf.get(key) + " year-olds or older)"));
}
}
using .sorted(Comparator.comparing(bookshelf::get))
was my idea of sorting them by the recommended age, which worked.
However, there exists an unexpected behavior that when the book's name is a single character ("A","b"), the program would also sort the keys alphabetically as though i made a comparator like Comparator.comparing(bookshelf::get).thenComparing(/*keys in keyset*/)
but would sometimes also sort like aAbB
AA bb give unsorted results
AAA bbb give semi-sorted results in one or two buckets
AAAA bbbb give semi- or completely sorted results
AAAAA bbbbb and onward give unsorted results.
Can anybody explain what is happening here, at compiler level or somehow let me make sense of this?