[英]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.