让我们考虑以下代码:
//...
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]
这是我的问题:如何制作 map 构造函数 TreeMap<>(fruits)
尊重传递给它的 map 的排序顺序?有没有一种优雅的方法可以根据原始 map 创建具有相同排序顺序的新 map ?
最佳答案
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) {
关于java - 在 Java 中从旧 map 创建新 map 的优雅方式,同时保持元素的排序相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38132576/