Ice*_*nte 1 java java-8 java-stream
假设我有一个品牌对象列表.POJO包含一个返回字符串的getName().我想Map<String, Brand>
用String作为名称来构建一个
...但我希望密钥不区分大小写.
如何使用Java流来完成这项工作?试:
brands.stream().collect(Collectors.groupingBy(brand -> brand.getName().toLowerCase()));
Run Code Online (Sandbox Code Playgroud)
不起作用,我认为是因为我没有正确使用groupBy.
将结果收集到不区分大小写的映射中
Map<String, Brand> map = brands
.stream()
.collect(
Collectors.toMap(
Brand::getName, // the key
Function.identity(), // the value
(first, second) -> first, // how to handle duplicates
() -> new TreeMap<String, Brand>(String.CASE_INSENSITIVE_ORDER))); // supply the map implementation
Run Code Online (Sandbox Code Playgroud)
Collectors#groupBy不会在这里工作,因为它返回一个Map<KeyType, List<ValueType>>,但你不想要List一个值,你只需要一个Brand,从我所理解的.
| 归档时间: |
|
| 查看次数: |
881 次 |
| 最近记录: |