Map<Integer, OperationCountVO> collect = operationInfos.stream().collect(Collectors.groupingBy(OperationCountVO::getCityId,
Collectors.reducing(new OperationCountVO(), (OperationCountVO v1, OperationCountVO v2) -> {
v1.setSurgeryCount(v1.getSurgeryCount() + v2.getSurgeryCount());
v1.setCityId(v2.getCityId());
return v1;
})));
Probably I want to group the operationInfos collection according to the cityId in it, and then if the cityId is the same, add the SurgeryCount of the object and return it, but now the first v1 is null,
execute v1.setSurgeryCount(v1. getSurgeryCount() v2.getSurgeryCount()); reported a null pointer, is there something wrong with where I wrote it?
If
v1
isnull
, it means that theoperationInfos
collection containsnull
, because it is grouped according to thecityId
ofOperationCountVO
, thenOperationCountVO
must not be null, it is recommended Addfilter
directly in front to filter it outI just commented and found... The possible reason for the error is that the first parameter in
Collectors.reducing
isnew OperationCountVO()
, if theOperationCountVO
object fromnew
has asurgeryCount
ofIf the Integer
type is not a basic type, so it is not initialized, thesurgeryCount
will benull
, and an error may be reported when doing thev1.getSurgeryCount() + v2.getSurgeryCount()
operation(ps: For the second parameter
BinaryOperator
inreducing
, it is best to encapsulate it into theOperationCountVO
object. The code looks more declarative... It’s too ugly to write code like this... haha. ..Or write it out, it’s better to write it as a static final variable, so it can be called everywhere)For example, add a
SurgeryCount
attribute mergedBinaryOperator
directly to this class, and the name issurgeryCountMerge
The following code can be changed to
After writing this, I actually found that the question may be a bit troublesome. In the end, it is just to return a
Map
, so it is recommended not to usegroupingBy
. After all, the grouping return result is a one-to-many structure, not a pair. 1 structure, then usetoMap
directly, just clickThis is much faster and no errors will be reported, haha