如何用Collectors.groupingBy将List<String>转为Map<Long, List<String>>并处理字符串
问题:将带前缀标识的字符串列表转换为分组Map
现有一个List<String>类型的resultList,内容如下:
["7802,Campaign submitted - audience list", "7802,Test Static Coupon", "7802,submit order", "7802,order creation failed", "7802,submit order", "8153,existing order test - resubmitting", "8153,existing order test - reorder", "8153,test", "8153,test", "8953,audience newly duplicated list"]
需要将其转换为Map<Long, List<String>>,具体要求:
- Map的键为字符串前缀的Long类型数字(如7802、8153等)
- Map的值为去掉前缀数字和逗号后的纯字符串列表
当前使用的分组代码返回的列表仍包含前缀数字和逗号:
resultList.stream().collect( Collectors.groupingBy(s -> Long.parseLong(s.substring(0, s.indexOf(','))), HashMap::new, Collectors.toCollection(ArrayList::new)));
请问如何修改代码以得到符合要求的输出?
解决方案
你当前的代码只处理了分组的键,没有对每个元素的值做裁剪处理。需要使用Collectors.mapping()先对每个字符串进行截取转换,再收集为列表。
修改后的代码如下:
Map<Long, List<String>> resultMap = resultList.stream() .collect(Collectors.groupingBy( // 提取键:截取逗号前的部分转为Long s -> Long.parseLong(s.substring(0, s.indexOf(','))), HashMap::new, // 转换值:截取逗号后的部分,再收集为ArrayList Collectors.mapping( s -> s.substring(s.indexOf(',') + 1), Collectors.toCollection(ArrayList::new) ) ));
关键修改点:
- 新增
Collectors.mapping()操作,对每个流元素执行s.substring(s.indexOf(',') + 1),跳过逗号直接获取后面的纯文本内容 - 转换后的元素通过
Collectors.toCollection(ArrayList::new)收集为列表,作为对应键的Map值
这样处理后,Map中的值列表就只会包含去掉前缀和逗号的目标字符串了。
内容的提问来源于stack exchange,提问作者murohima_1
相关产品推荐
相关产品推荐

