在java恢复插入顺序中合并Map

时间:2016-08-29 21:13:35

标签: java

我有3张相同类型的地图。 map1是最高优先级的map,map2是次优先级,map3是最低优先级。

 Map<Integer, String> map1 = {2="two", 4="four"};
 Map<Integer, String> map2 = {2="twotwo", 1="one",3="three"};
 Map<Integer, String> map3 = {1="oneone", 5="five"};

最后我希望合并的地图就像

 Map<Integer, String> mergedmap = {2="two", 4="four",1="one",3="three",5="five"};

要遵循的基本算法

  1. 将map1的所有条目添加到合并的地图。
  2. 将map2的条目添加到合并的地图,如果其密钥已存在则跳过条目。
  3. 将map3的条目添加到合并的地图,如果其密钥已存在则跳过条目。
  4. 我试过了

        Map<Integer, String> mergeMap = new HashMap<Integer,String>(map3);
        mergeMap.putAll(map2);
        mergeMap.putAll(map1);
    

    结果是

       Map<Integer, String> mergedmap = {1="one", 2="two", 3="three", 4="four", 5="five"};
    

    数据是正确的但不是我需要的顺序。怎么做到这一点?以下是测试类

    import java.util.HashMap;
    import java.util.Map;
    
    
    public class MapTest {
    public static void main(String[] args){
    
         Map<Integer, String> map1 = new HashMap<Integer, String>();
         map1.put(2, "two");
         map1.put(4, "four");
    
         Map<Integer, String> map2 =  new HashMap<Integer, String>();
         map2.put(2, "twotwo");
         map2.put(1, "one");
         map2.put(3, "three");
    
         Map<Integer, String> map3 = new HashMap<Integer, String>();
         map3.put(1, "oneone");
         map3.put(5, "five");
    
         Map<Integer, String> mergeMap = new HashMap<Integer,String>(map3);
         mergeMap.putAll(map2);
         mergeMap.putAll(map1);
         System.out.println(mergeMap);
    
    }
    }
    

2 个答案:

答案 0 :(得分:1)

我想知道你为什么要在地图中维护一个序列,但如果确实这样做了,你应该使用linkedHashMap。看到这个 -

public static void main(String[] args) {
    Map<Integer, String> map1 = new LinkedHashMap<>();
    map1.put(2, "two");
    map1.put(4, "four");

    Map<Integer, String> map2 = new LinkedHashMap<>();
    map2.put(2, "twotwo");
    map2.put(1, "one");
    map2.put(3, "three");

    Map<Integer, String> map3 = new LinkedHashMap<>();
    map3.put(1, "oneone");
    map3.put(5, "five");

    Iterator<Entry<Integer, String>> iterator2 = map2.entrySet().iterator();

    while (iterator2.hasNext()) {
        Entry<Integer, String> entry = iterator2.next();
        if (!map1.containsKey(entry.getKey())) {
            map1.put(entry.getKey(), entry.getValue());
        }
    }

    System.out.println(map1);

}

输出 -

{2=two, 4=four, 1=one, 3=three}

自己尝试map3。

答案 1 :(得分:1)

您可以使用putIfAbsent方法确保正确的条目位于地图中。

Map<Integer, String> mergedMap = new HashMap<>(map1);
map2.forEach((k, v) -> mergedMap.putIfAbsent(k, v);
map3.forEach((k, v) -> mergedMap.putIfAbsent(k, v);

最好在使用条目时进行排序,而不是在创建条目时进行排序:

mergedMap.entrySet().stream()
    .sorted(Map.Entry.comparingByValue)
    .forEach(System.out::println);