【问题标题】:Swap keys with values and vice versa of HashMap [duplicate]用HashMap的值交换键,反之亦然[重复]
【发布时间】:2016-07-26 12:25:19
【问题描述】:

这是一个入门问题,我想用值交换键,反之亦然 HashMap。这是我迄今为止尝试过的。

import java.util.HashMap;
import java.util.Map;

class Swap{
    public static void main(String args[]){

        HashMap<Integer, String> s = new HashMap<Integer, String>();

        s.put(4, "Value1");
        s.put(5, "Value2");

        for(Map.Entry en:s.entrySet()){
            System.out.println(en.getKey() + " " + en.getValue());
        }
    }
}

【问题讨论】:

    标签: java hashmap


    【解决方案1】:

    您需要一个新的Map,因为您示例中的键和值具有不同的类型。

    在 Java 8 中,这可以通过创建原始 Map 的条目的 Stream 并使用 toMap Collector 生成新的 Map 来轻松完成:

    Map<String,Integer> newMap = 
        s.entrySet().stream()
                    .collect(Collectors.toMap(Map.Entry::getValue,Map.Entry::getKey));
    

    【讨论】:

    • 这非常简单优雅,但我使用的是早期版本。
    • @HiteshkumarMisro 好吧,在早期的 Java 版本中,您必须创建一个新的 Map,使用循环遍历原始 Map 的 entrySet(),并为每个条目调用 newMap.put(entry.getValue(),entry.getKey()) .
    【解决方案2】:

    按照 Eran 的建议,我编写了一个简单的演示,将一个 hashmap 的键和值与另一个 hashmap 交换。

    import java.util.HashMap;
    import java.util.Map;
    
    class Swap {
        public static void main(String args[]) {
    
            HashMap<Integer, String> s = new HashMap<Integer, String>();
    
            s.put(4, "Value1");
            s.put(5, "Value2");
    
            for (Map.Entry en : s.entrySet()) {
                System.out.println(en.getKey() + " " + en.getValue());
            }
    
            /*
             * swap goes here
             */
            HashMap<String, Integer> newMap = new HashMap<String, Integer>();
            for(Map.Entry<Integer, String> entry: s.entrySet()){
                newMap.put(entry.getValue(), entry.getKey());
            }
    
            for(Map.Entry<String, Integer> entry: newMap.entrySet()){
                System.out.println(entry.getKey() + " " + entry.getValue());
            }
        }
    }
    

    【讨论】:

    • 对我来说很棒的作品
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-28
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 2016-01-27
    • 1970-01-01
    相关资源
    最近更新 更多