win*_*ute 3 java sorting dictionary case-insensitive treemap
我们考虑以下代码:
//...
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());
}
Run Code Online (Sandbox Code Playgroud)
- 执行结果将是
[Apple, banana, cherry, Dragon_Fruit, Papaya ]
Run Code Online (Sandbox Code Playgroud)
在那之后,我正在打电话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());
}
Run Code Online (Sandbox Code Playgroud)
- 后者的结果println()将如下所示:
[Apple, Dragon_Fruit, banana, cherry]
Run Code Online (Sandbox Code Playgroud)
- 我希望看到这个:
[Apple, banana, cherry, Dragon_Fruit]
Run Code Online (Sandbox Code Playgroud)
这是我的问题:如何使地图构造函数TreeMap<>(fruits)尊重传递给它的地图的排序顺序?是否有一种优雅的方法来创建基于原始地图的新地图,具有相同的排序顺序?
TreeMap有一个构造函数SortedMap保持相同Comparator(因此,顺序).但是,由于你将你的传递TreeMap作为a Map,所以不使用这个构造函数 - 而是调用aMap的构造函数,并且丢失了顺序.
长话短说 - 改变getApprovedFruits'签名使用a SortedMap,你应该没问题:
public Map<String, Integer> getApprovedFruits
(SortedMap<String, Integer> fruits, Set<String> whiteListedFruitNames) {
Run Code Online (Sandbox Code Playgroud)