【发布时间】:2020-09-23 18:21:15
【问题描述】:
在https://java-programming.mooc.fi/part-10/2-interface-comparable 上进行“文学”练习时,我在尝试对 HashMap 中的键值对进行排序时发现了一种非常奇怪的行为,而没有将任何内容复制到 TreeMap。我应该通过创建 Book 类并将它们添加到 List 来添加书籍。但是我想尝试不创建新类,所以选择了 HashMap。我的代码如下:
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)"));
}
}
使用.sorted(Comparator.comparing(bookshelf::get)) 是我按照推荐年龄对它们进行排序的想法,这很有效。
但是,存在一个意外行为,即当书名是单个字符(“A”、“b”)时,程序还会按字母顺序对键进行排序,就好像我做了一个比较器,如 Comparator.comparing(bookshelf::get).thenComparing(/*keys in keyset*/),但有时会也排序为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.
任何人都可以在编译器级别解释这里发生了什么,或者让我理解一下吗?
【问题讨论】:
-
不是你的问题的答案,但你为什么不写一本书类并添加一个
compareTo()方法?充分利用面向对象! -
您仅根据键对键集进行了排序。如果要排序映射,请使用 entryset() 以避免在迭代时调用。
标签: java sorting hashmap java-stream method-reference