简体   繁体   English

根据第二个 map 中的键顺序对 Map 进行排序

[英]Sort Map with respect to order of keys in second map

I've 2 LinkedHashMaps<String, SomeList>, say Map1 , Map2 The keys in both the maps are same but orders can be different.我有 2 个LinkedHashMaps<String, SomeList>,比如说Map1 , Map2两个地图中的键是相同的,但顺序可以不同。

Example:例子:

Map1:地图1:

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

Map2:地图2:

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.我想按键对 Map2 进行排序,使其顺序与 Map1 相同。

Result I'm looking for:我正在寻找的结果:

Map2:地图2:

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

Just create a new LinkedHashMap by iterating over the keys of map1 and obtaining for each key the corresponding value of map2 :只需通过迭代map1的键并为每个键获取map2的相应值来创建一个新的LinkedHashMap

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM