英文:
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<String,String> sorted =
map1.keySet()
.stream()
.collect(Collectors.toMap(Function.identity(),
map2::get,
(v1,v2)->v1,
LinkedHashMap::new));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论