我有一个List<String>
,我必须Map
通过将相同的长度String
s分组为,将长度转换为List
,将String
长度作为键,并按排序顺序进行转换。可以使用-
Map<Integer, List<String>> result = new TreeMap<>();
for (String str : list) {
if (!result.containsKey(str.length())) {
result.put(str.length(), new ArrayList<>());
}
result.get(str.length()).add(str);
}
我们如何使用Java 8流来做到这一点?
您可以使用流来做到这一点:
Map<Integer, List<String>> result = list.stream()
.collect(Collectors.groupingBy(
String::length, // use length of string as key
TreeMap::new, // create a TreeMap
Collectors.toList())); // the values is a list of strings
这将通过Collectors.groupingBy
接受3个参数的重载来收集流:键映射器函数,映射的提供者和下游的收集器。
但是,有一种更紧凑的方式来执行此操作,而无需使用流:
Map<Integer, List<String>> result = new TreeMap<>();
list.forEach(s -> result.computeIfAbsent(s.length(), k -> new ArrayList<>()).add(s));
使用List.forEach
并Map.computeIfAbsent
实现您想要的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句