按第二个地图中键的顺序排序地图。

huangapple go评论82阅读模式
英文:

Sort Map with respect to order of keys in second map

问题

Map1:

Hello, Value1
How, Value2
Are, Value3
You, Value4

Map2:

Hello, Value1
You, Value4
Are, Value3
How, Value2

我想要按照键对Map2进行排序,以使其顺序与Map1相同。

期望的结果:

Map2:

Hello, Value1
How, Value2
Are, Value3
You, Value4
英文:

I've 2 LinkedHashMaps<String, SomeList>, say Map1, Map2 The keys in both the maps are same but orders can be different.

Example:

Map1:

Hello, Value1
How, Value2
Are, Value3
You, Value4

Map2:

Hello, Value1
You, Value4
Are, Value3
How, Value2

I want to sort the Map2 by keys such that its order then becomes same as Map1.

Result I'm looking for:

Map2:

Hello, Value1
How, Value2
Are, Value3
You, Value4

答案1

得分: 3

只需通过迭代map1的键并获取每个键对应的map2的值来创建一个新的LinkedHashMap

Map<String, String> sorted =
    map1.keySet()
        .stream()
        .collect(Collectors.toMap(Function.identity(),
                                  map2::get,
                                  (v1, v2) -> v1,
                                  LinkedHashMap::new));
英文:

Just create a new LinkedHashMap by iterating over the keys of map1 and obtaining for each key the corresponding value of map2:

Map&lt;String,String&gt; sorted =
    map1.keySet()
        .stream()
        .collect(Collectors.toMap(Function.identity(),
                                  map2::get,
                                  (v1,v2)-&gt;v1,
                                  LinkedHashMap::new));

huangapple
  • 本文由 发表于 2020年8月11日 17:22:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/63355296.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定