函数式接口改造
private TopModel generateTopDetailModel(TopModel topModel, List<PlayerWithData> playerWithDataList) {
List<TopDetailModel> shotsTopDetail = playerWithDataList.stream()
.filter(p -> p.getShots() != null && p.getShots() != 0)//要过滤掉空值再比较,且要过滤掉0值
.sorted(Comparator.comparing(PlayerWithData::getShots).reversed()
.thenComparing(PlayerWithData::getName)).
limit(3).map(StatsPlayer -> {
TopDetailModel model = new TopDetailModel();
BeanUtils.copyProperties(StatsPlayer, model);
model.setDataCount(StatsPlayer.getShots());
return model;
}).collect(Collectors.toList());
topModel.setShots(shotsTopDetail);
List<TopDetailModel> maxDribbSpTopDetail = playerWithDataList.stream().
filter(p -> p.getMaxDribbSp() != null && p.getMaxDribbSp() != 0.0)
.sorted(Comparator.comparing(PlayerWithData::getMaxDribbSp).reversed()
.thenComparing(PlayerWithData::getName)).
limit(3).map(StatsPlayer -> {
TopDetailModel model = new TopDetailModel();
BeanUtils.copyProperties(StatsPlayer, model);
model.setDataCount(StatsPlayer.getMaxDribbSp());
return model;
}).collect(Collectors.toList());
topModel.setMaxDribbSp(maxDribbSpTopDetail);
//省略N个字段的获取设值...
return topModel;
}
private List<TopDetailModel> setIntegerTopModel(List<PlayerWithData> playerWithDataList,
Function<PlayerWithData, Integer> function, Integer count) {
return playerWithDataList.stream()
.filter(p -> function.apply(p) != null && function.apply(p) != 0)
.sorted(Comparator.comparing(function).reversed()
.thenComparing(PlayerWithData::getName)).
limit(count).map(stasPlayer -> {
TopDetailModel model = new TopDetailModel();
BeanUtils.copyProperties(stasPlayer, model);
model.setDataCount(function);
return model;
}).collect(Collectors.toList());
}
之后每个参数传入函数方法调用设值即可:
topModel.setShots(setIntegerTopModel(playerWithDataList, PlayerWithData::getShots, count));
字符串操作
for (PenaltyModel penaltyModel : penaltyModels) {
String eventType = "PENALTY.";
if (penaltyModel.getIsGoal()) {
eventType = eventType + "TRUE";
} else {
eventType = eventType + "FALSE";
}
......
每次循环都会创建新对象,造成内存资源浪费
}
String为字符串常量,而StringBuilder和StringBuffer均为字符串变量,
即String对象一旦创建之后该对象是不可更改的,但后两者的对象是变量,是可以更改的
String:适用于少量的字符串操作的情况
StringBuilder:适用于单线程下在字符缓冲区进行大量操作的情况
StringBuffer:适用多线程下在字符缓冲区进行大量操作的情况
枚举命名
建议带上 Enum 后缀,枚举成员名称需要全大写,单词间用下划线隔开
正例:BallEnum 反例:BallType
避免在循环中进行数据库操作
private void uploadTeamConfig(List<TeamConfig> teamConfigList, String matchId) {
if (!CollectionUtils.isEmpty(teamConfigList)) {
for (TeamConfig teamConfig : teamConfigList) {
PerMatchTeamConfig perMatchTeamConfig = new PerMatchTeamConfig();
BeanUtils.copyProperties(teamConfig, perMatchTeamConfig);
perMatchTeamConfig.setMatchId(matchId);
perMatchTeamConfigService.saveOrUpdateByMatchIdAndTeamId(perMatchTeamConfig);
}
}
}
网友评论