流最小值无法正常工作,有时返回最大值而不是最小值

时间:2019-05-14 08:29:57

标签: java

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,但如果返回2000,则返回12000,在大多数情况下,它也将返回2000。

5 个答案:

答案 0 :(得分:2)

这是因为您将其与String进行了比较。 将fee更改为IntegerLong类型。

答案 1 :(得分:2)

那是因为您使用的是String,但是正如您指定的那样,这是必需的。 因此,您必须以这种方式更改流:

OptionalInt min = studentList.stream()
    .map(Student::getFee)
    .mapToInt(Integer::parseInt)
    .min();

通过这种方式,您将String转换为Int,然后采用最小值。

如果您的值带有小数点,请改用mapToDouble

答案 2 :(得分:2)

将映射解析到列表中的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();
}

答案 3 :(得分:2)

您正在比较String而不是Integer

您可以通过提供将Comparator解析为String(如果需要,可以选择Integer的{​​{1}}来解决此问题:

double

答案 4 :(得分:1)

您正在比较String值,应该比较数字值以获得预期的结果,例如doublesints。将fee字段的类型更改为DoubleLongInteger

按字母顺序比较字符串,因此比较300012000会使3000看起来更大,因为在第一个字母比较时3> 1

相关问题