smallest element from unsorted arraylist in java

  • A+

I have a dto class which stores some studentid and marks of particular subject. basically like this.

List<StudentInfoDTO> studentInfoDTO = new ArrayList<>(); 

where StudentInfoDTO is like below

public class StudentInfoDTO {      Long studentId;     Short marks;  } 

Now I want the student id who has smallest marks.

I tried below but not giving expected result.

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;     }                        } 


You can also use streams, it has a convenient method called min(); 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: