Stream min not working sometimes returning max value instead of min

Deepika R :
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;

public class GetMiles {
    public static void main(String args[]) {
        List<Student> studentList = new ArrayList<>();
        Student s = new Student();
        s.setFee("12000");
        studentList.add(s);
        Student s1 = new Student();
        s1.setFee("3000");
        studentList.add(s1);
        Optional<Student> optionalStudent = 
    studentList.stream().min(Comparator.comparing(Student::getFee));
        if (optionalStudent.isPresent()) {
            System.out.println(optionalStudent.get().getFee());
        }
    }
static class Student {
        private String fee;
        public String getFee() {
            return this.fee;
        }
        public void setFee(String fee) {
            this.fee = fee;
        }
    }
   }

in above example it should return 3000 but returning 12000 if we will give 2000 and 3000 it will return 2000 also in most of the scenario its working fine but not for all.

Imran.Khan :

Parse map to int in your list and then get min of fee like below example code :

Optional<Integer> optionalVal = studentList.stream().map(l -> 
Integer.parseInt(l.getFee())).min(Comparator.comparingInt(k -> k));
if(optionalVal.isPresent()) {
String minFee = String.valueOf(optionalVal.get());
   Optional<Student> studentObj = studentList.stream().filter(p -> 
   minFee.equals(p.getFee())).findFirst();
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=111903&siteId=1