我们考虑以下代码:
//...
public Map<String, Integer> getFruits() throws SomeException {
QueryResult[] queryResults = queryFruits();
Map<String, Integer> fruits = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
for (QueryResult qr : queryResults) {
fruits.put(qr.getField("Name").toString(), (Integer) rec.getField("ArticleNumber"));
}
return fruits;
}
//...
public static void main(String args[]) {
App app = new App();
Map<String, Integer> originalFruits = app.getFruits();
System.out.println(originalFruits.keySet());
}
– 执行结果将是
[Apple, banana, cherry, Dragon_Fruit, Papaya ]
之后,我正在调用getApprovedFuits()并将originalFruits传递给它,以及whiteListedFruitNames:
public Map<String, Integer> getApprovedFruits(Map<String, Integer> fruits, Set<String> whiteListedFruitNames) {
Map<String, Integer> approvedFruits = new TreeMap<>(fruits);
approvedFruits.keySet().retainAll(whiteListedFruitNames);
return approvedFruits;
}
//...
public static void main(String[] args) {
App app = new App();
Map<String, Integer> originalFruits = app.getFruits();
// v
Set<String> whiteListedFruitNames = new HashSet<>(Arrays.asList("Apple",
"banana",
"cherry",
"Dragon_Fruit",
"kiwi",
"Pineapple"));
Map<String, Integer> approvedFruits = getApprovedFruits(originalFruits, whiteListedFruitNames);
System.out.println(approvedFruits.keySet());
}
– 后一个println()的结果将如下所示:
[Apple, Dragon_Fruit, banana, cherry]
– 我希望看到这个:
[Apple, banana, cherry, Dragon_Fruit]
这是我的问题:如何使地图构造函数TreeMap<>(fruits)尊重传递给它的地图的排序顺序?是否有一种优雅的方法来创建基于原始地图的新地图,具有相同的排序顺序?
解决方法:
TreeMap有一个constructor from a SortedMap
,它保留了相同的Comparator(因此,订购).但是,由于您将TreeMap作为Map传递,因此不使用此构造函数 – 而是调用constructor from a Map
,并且丢失了排序.
长话短说 – 改变getApprovedFruits的签名以使用SortedMap,你应该没问题:
public Map<String, Integer> getApprovedFruits
(SortedMap<String, Integer> fruits, Set<String> whiteListedFruitNames) {