我有一个dto类,其中存储了一些学生ID和特定学科的分数。基本上是这样的
List<StudentInfoDTO> studentInfoDTO = new ArrayList<>();
StudentInfoDTO如下所示
public class StudentInfoDTO {
Long studentId;
Short marks;
}
现在,我想要分数最小的学生证。
我在下面尝试过,但没有给出预期的结果。
int smallest = 0;
for(int i = 0; i < studentInfoDTO.size(); i++) {
smallest = studentInfoDTO.get(i).getMarks();
int x = studentInfoDTO.get(i).getMarks();
if (x < smallest) {
smallest = x;
}
}
最佳答案
您可以通过多种方式实现此目的:
Java 1.4样式:
StudentInfoDTO smallest = null;
for (int i = 0; i < studentInfoDTO.size(); i++) {
StudentInfoDTO current = studentInfoDTO.get(i);
if (smallest == null || current.getMarks() < smallest.getMarks() ) {
smallest = current;
}
}
Java 5样式:
StudentInfoDTO smallest = null;
for (StudentInfoDTO current : studentInfoDTO) {
if (smallest == null || current.getMarks() < smallest.getMarks()) {
smallest = current;
}
}
Java 8样式:
StudentInfoDTO smallest = studentInfoDTO.stream()
.min(Comparator.comparing(StudentInfoDTO::getMarks))
.get();
关于java - Java中未排序的arraylist中的最小元素,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52779261/