我想把这段代码转换成等价的流或for-each循环
for (Studentauditlog st: studentauditloglist) {
String columnValue = callEntityGetterMethod(st, column);
if (StringUtils.isNotBlank(columnValue)) {
if (response.containsKey(columnValue)) {
Long count = (response.get(columnValue) == null)? 0L : response.get(columnValue);
response.put(columnValue, count + 1);
} else {
response.put(columnValue, 1L);
}
}
}
现有代码计算一个response
映射,其中非空白字符串列是键,映射值是键的频率。
这可以通过Stream::map
,Stream::filter
的序列来实现,以获得列值,这些列值使用Collectors.groupingBy
和Collectors.counting
作为下游收集器进行分组。
见下面的实现:
Map<String, Long> response = studentauditloglist
.stream() // Stream<Studentauditlog >
.map(st -> callEntityGetterMethod(st, column))
.filter(StringUtils::isNotBlank) // Stream<String>
.collect(Collectors.groupingBy(
cv -> cv, // or Function.identity()
Collectors.counting()
));