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;
}
}
}
在上面的示例中,如果我们给出2000,则应返回3000,但应返回12000,而在大多数情况下,它应返回2000,但也将返回2000。
最佳答案
解析映射到列表中的int,然后获取最低费用,如下例代码所示:
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();
}