java 中未排序数组列表中的最小元素

smallest element from unsorted arraylist in java

我有一个 dto class,它存储了一些学生 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;
    }                       
}

在您的代码中,您一次又一次地分配 smallest,而这意味着一直以来都具有最小的标记。此外,您还需要维护分数最低的学生的 ID,否则之后您将无法访问它。

int smallest = MAX_MARKS;
int id = -1;
for(int i =0; i<studentInfoDTO.size();i++) {
   int x = studentInfoDTO.get(i).getMarks();
   if (x < smallest) {
      smallest = x;
      i = studentInfoDTO.get(i).getStudentId();
   }
}
if(id!=-1){
   System.out.println("id of smallest marks student : " + id);
}

你也可以使用流,它有一个方便的方法叫做min()

studentInfoDTO.stream().min(Comparator.comparing(StudentInfoDTO::getMarks));
Integer minMarks = studentInfoDTO
      .stream()
      .mapToInt(StudentInfoDTO::getMarks)
      .min().orElseThrow(NoSuchElementException::new);

您可以通过多种方式实现此目的:

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();

问题是您正在比较相同的 x 和最小的 x。所以你的 if 条件总是失败。这将解决问题。

int smallest = studentInfoDTO.get(0).getMarks();
for(int i =0; i<studentInfoDTO.size() - 1;i++) 
{
 int x = studentInfoDTO.get(i + 1).getMarks();
 if (x < smallest) {
    smallest = x;
 }
}