下面的代码怎么用 stream 实现呢?想了半天绕不明白,stram api 用的太少了
public void countBlame(List<Blame> blames) {
final HashMap<String, TotalResult> map = map();
for (Blame author : blames) {
if (map.containsKey(author.getName())) {
final TotalResult totalResult = map.get(author.getName());
totalResult.setRows(totalResult.getRows() + author.getRows());
}else{
final TotalResult totalResult = new TotalResult(author.getName(), 0, 0, author.getRows(), null);
map.put(author.getName(), totalResult);
results.add(totalResult);
}
}
}
private HashMap<String,TotalResult> map() {
final HashMap<String, TotalResult> stringTotalResultHashMap = new HashMap<>();
for (TotalResult result : results) {
stringTotalResultHashMap.put(result.getName(), result);
}
return stringTotalResultHashMap;
}
1
GTim 2019-01-25 13:57:19 +08:00
|
2
EXE 2019-01-25 13:57:33 +08:00
results.stream().collect(Collectors.toMap(TotalResult::getName));
|
3
Volio 2019-01-25 14:13:11 +08:00
List<TotalResult> result = blames.stream().collect(Collectors.groupingBy(Blame::getName, Collectors.mapping(Blame::getRows, Collectors.reducing(0, Integer::sum)))).entrySet().stream().map(o -> new TotalResult(o.getKey(),0,0,o.getValue(),null)).collect(Collectors.toList());
|
4
yidinghe 2019-01-25 14:16:43 +08:00 1
|
5
GTim 2019-01-25 14:20:59 +08:00
第一个
blames.stream().map(author => new TotalResult(author.getName(), 0, 0, author.getRows(), null)).collect(Collectors.toMap(TotalResult::getName, result -> result,(oldValue,newValue)-> {oldValue.setRows(oldValue.getRows() + newValue.getRows();return oldValue;})) |
7
daemonk 2019-01-25 14:28:33 +08:00
Map<String, TotalResult> map = blames.stream().collect(
Collectors.toMap( Blame::getName, blame -> new TotalResult(blame.getName(), 0, 0, blame.getRows(), null), (tr1, tr2) -> { tr1.setRows(tr1.getRows() + tr2.getRows()); return tr1; }, HashMap::new)); List<TotalResult> results = new ArrayList<>(map.values()); |
8
thinkmore 2019-01-29 09:56:18 +08:00
为啥我看着 lambda 这么费力
|