java - 将 Map.Entry 列表转换为 LinkedHashMap
问题描述
我有一个列表,我需要将它转换为 Map,但键的顺序相同,所以我需要转换为 LinkedHashMap。我需要这样的东西:
list.stream().collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
但使用具体类型的地图,例如:
list.stream().collect(Collectors.toCollection(LinkedHashMap::new))
是否可以结合上述两种变体?
解决方案
是的,只需使用Collectors.toMap
包含合并功能和地图供应商的变体:
<T, K, U, M extends Map<K, U>> Collector<T, ?, M> java.util.stream.Collectors.toMap(Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends U> valueMapper, BinaryOperator<U> mergeFunction, Supplier<M> mapSupplier)
使用简单的合并函数(选择第一个值)将如下所示:
LinkedHashMap<KeyType,ValueType> map =
list.stream().collect(Collectors.toMap(Map.Entry::getKey,
Map.Entry::getValue,
(v1,v2)->v1,
LinkedHashMap::new));
推荐阅读
- android - 发送 Java 类作为函数参数
- jenkins-pipeline - Jenkins Pipeline 中的变量扩展
- ios - 在 Extension Swift 4.2 中更改导航栏、表格视图、集合视图的颜色属性和图像
- asp.net - 上传和更新excel文件
- javascript - 我有多行字符串现在我想打印那些包含特定子字符串的行
- combobox - Vaadin 8 ComboBox将项目设置为html不起作用
- angularjs - 在angularjs中,为什么ng-model的值在select中保持不变?
- android - 为什么在工具栏上执行汉堡到箭头动画时会有不同的动画?
- java - Gradle 同步失败
- c# - n秒后的凝视触发事件 - Unity