double average = students.stream().mapToDouble(Student::getScore).average().orElse(0D);
时间: 2024-08-12 15:07:23 浏览: 105
这段Java代码使用了Java 8的Stream API来计算学生列表中成绩(假设为double类型)的平均值。`students` 是一个`Student`对象的集合,每个`Student`有一个名为`getScore()`的方法来获取其分数。
这里是逐步解释:
1. `students.stream()`:创建一个从`students`集合流化的操作。这允许我们对集合中的每个元素执行连续的操作。
2. `.mapToDouble(Student::getScore)`:将每个`Student`对象转换为其分数(double类型)。`Student::getScore`是一个方法引用,它表示调用`Student`对象的`getScore`方法并返回结果。
3. `.average()`:对所有映射后的分数进行平均计算。
4. `.orElse(0D)`:如果流为空(即没有学生),则返回默认值0.0(double类型)。`orElse()`是一个可选操作,当流中没有元素时提供备选值。
所以,整个表达式的结果就是`students`集合中所有学生的平均成绩,如果集合为空则返回0.0。示例中`average()`会返回一个`OptionalDouble`,但因为后面有`.orElse(0D)`,所以我们可以直接得到一个double类型的值。
相关问题
优化这段java代码 //通过域账号名称 调用userSdk获取 对应ID List<String> sendUserNameList = form.getOperationScoreDTOList() .stream().map(OperationScoreDTO::getSenderName).distinct().collect(Collectors.toList()); List<String> receiverUserNameList = form.getOperationScoreDTOList() .stream().map(OperationScoreDTO::getReceiverName).distinct().collect(Collectors.toList()); List<FindOneByUsernameVo> sendUserList = userServiceSdk.findByUsernames(sendUserNameList); List<FindOneByUsernameVo> receiverUserList = userServiceSdk.findByUsernames(receiverUserNameList); Map<String, Integer> senderMap = sendUserList .stream() .collect(Collectors.toMap(FindOneByUsernameVo::getUsername, FindOneByUsernameVo::getTeclibUserId)); Map<String, Integer> receiverMap = receiverUserList .stream() .collect(Collectors.toMap(FindOneByUsernameVo::getUsername, FindOneByUsernameVo::getTeclibUserId)); for (OperationScoreDTO operationScoreDTO : form.getOperationScoreDTOList()) { Integer senderId = senderMap.get(operationScoreDTO.getSenderName()); if (senderId == null) { throw new BizException("获取发送者失败"); } Integer receiverId = receiverMap.get(operationScoreDTO.getSenderName()); if (receiverId == null) { throw new BizException("获取接收者失败"); } Short score = operationScoreDTO.getScore(); String remark = operationScoreDTO.getRemark(); OperationScoreEntity os = new OperationScoreEntity(); os.setSendId(senderId); os.setReceiverId(receiverId); os.setEvent(score.toString()); os.setRemark(remark); os.setSendTime(LocalDate.now()); operationScoreRepository.save(os); String event = ScoreEventConstant.BONUS_SCORE; String module = ScoreModuleConstant.BONUS_SCORE; String payload = String.format("osId:%d;receiver:%d;remark:%s;score:%s", os.getId(), receiverId, remark, score); UserScoreEntity userScore = new UserScoreEntity(); userScore.setUserId(receiverId); userScore.setModule(module); userScore.setEvent(event); userScore.setPayload(payload); userScore.setOperationTime(operationScoreDTO.getOperationTime()); userScore.setScore(score); Integer totalScore = this.findTotalScoreByUserId(receiverId); userScore.setTotal(Math.max(totalScore + score, 0)); userScoreRepository.save(userScore); } return Boolean.TRUE;
在这段代码中,你可以考虑以下优化措施:
1. 将重复的代码提取为方法:将获取用户名列表和调用 `userServiceSdk.findByUsernames` 的逻辑提取为一个方法,这样可以减少重复代码。
2. 使用 `forEach` 替代 `for` 循环:使用流的 `forEach` 方法可以简化循环的书写,更加简洁和直观。
3. 使用批量插入:使用批量插入操作可以减少数据库交互次数,提高性能。
下面是优化后的代码示例:
```java
List<String> sendUserNameList = form.getOperationScoreDTOList()
.stream().map(OperationScoreDTO::getSenderName).distinct().collect(Collectors.toList());
List<String> receiverUserNameList = form.getOperationScoreDTOList()
.stream().map(OperationScoreDTO::getReceiverName).distinct().collect(Collectors.toList());
Map<String, Integer> senderMap = getUserIdsByUsernames(sendUserNameList);
Map<String, Integer> receiverMap = getUserIdsByUsernames(receiverUserNameList);
form.getOperationScoreDTOList().forEach(operationScoreDTO -> {
Integer senderId = senderMap.get(operationScoreDTO.getSenderName());
if (senderId == null) {
throw new BizException("获取发送者失败");
}
Integer receiverId = receiverMap.get(operationScoreDTO.getSenderName());
if (receiverId == null) {
throw new BizException("获取接收者失败");
}
Short score = operationScoreDTO.getScore();
String remark = operationScoreDTO.getRemark();
OperationScoreEntity os = new OperationScoreEntity();
os.setSendId(senderId);
os.setReceiverId(receiverId);
os.setEvent(score.toString());
os.setRemark(remark);
os.setSendTime(LocalDate.now());
operationScoreRepository.save(os);
String event = ScoreEventConstant.BONUS_SCORE;
String module = ScoreModuleConstant.BONUS_SCORE;
String payload = String.format("osId:%d;receiver:%d;remark:%s;score:%s",
os.getId(), receiverId, remark, score);
UserScoreEntity userScore = new UserScoreEntity();
userScore.setUserId(receiverId);
userScore.setModule(module);
userScore.setEvent(event);
userScore.setPayload(payload);
userScore.setOperationTime(operationScoreDTO.getOperationTime());
userScore.setScore(score);
Integer totalScore = this.findTotalScoreByUserId(receiverId);
userScore.setTotal(Math.max(totalScore + score, 0));
userScoreRepository.save(userScore);
});
return Boolean.TRUE;
private Map<String, Integer> getUserIdsByUsernames(List<String> usernames) {
List<FindOneByUsernameVo> userList = userServiceSdk.findByUsernames(usernames);
return userList.stream()
.collect(Collectors.toMap(FindOneByUsernameVo::getUsername, FindOneByUsernameVo::getTeclibUserId));
}
```
通过上述优化,你可以减少代码重复,提高代码的可读性和维护性,并且减少数据库交互次数,提高性能。
Iterator<yuanshishujuceshijieguo> allrecords = Listrecords.iterator(); while (allrecords.hasNext()) { yuanshishujuceshijieguo ps1 = new yuanshishujuceshijieguo(); ps1 = allrecords.next(); int id = ps1.getId(); int uid = ps1.getUid(); int pid = ps1.getPid(); double score = ps1.getScore(); System.out.println("用户id=:" + uid + " 商品id=: " + pid + " 评分=:" + score); //request.getSession().setAttribute("yuanshishujuceshijieguo", ps1); //ps1.setScore(Double.(score,4)); psArray.add(ps1); }
这段代码的作用是从Listrecords列表中遍历所有的记录,并将每条记录的id、uid、pid和score等属性值取出来,然后使用System.out.println()方法将这些属性值打印出来。同时,将每条记录存储在名为psArray的ArrayList类型的数组中。具体的遍历过程请参考下面的示例代码:
```
Iterator<yuanshishujuceshijieguo> allrecords = Listrecords.iterator();
while (allrecords.hasNext()) {
yuanshishujuceshijieguo ps1 = allrecords.next();
int id = ps1.getId();
int uid = ps1.getUid();
int pid = ps1.getPid();
double score = ps1.getScore();
System.out.println("用户id=:" + uid + " 商品id=: " + pid + " 评分=:" + score);
psArray.add(ps1); // 将记录存储在数组中
}
```
在上面的代码中,每次迭代器调用next()方法时,都会返回Listrecords列表中的下一个元素,存储在名为ps1的变量中,然后可以使用ps1对象的各种方法来获取记录中的属性值。获取完属性值后,使用System.out.println()方法将记录的属性值打印出来,并将该记录存储在psArray数组中。
阅读全文