java - 在 Java 中从旧 map 创建新 map 的优雅方式,同时保持元素的排序相同

标签 java sorting dictionary treemap case-insensitive

让我们考虑以下代码:

//...

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/

相关文章:

java - Spring MVC框架非常基本的Dispatcher问题

带有文件的 java 代码在 eclipse 中工作,但在 cmd 中不工作

angular - 在 Angular MatTable 中排序后如何获取更新的 Viewchildren 引用

java - 如何从上到下对轮廓进行排序: Opencv , Android

.net - 我该如何解决?错误 : Select is not a member of 'System.Collections.Generic.List(Of String)'

c++ - 将 map<>::iterator 作为 map<>::const_iterator &

python - 在python中对字母数字字典键进行排序

java - 如何使用单独的类加载器并在同一个 JVM 中运行? (OSGI)

java - 为什么我不能在泛型方法中对 Integer 和 Double 使用 + 运算符?

python - 通过列表理解或任何其他方法解决嵌套字典迭代