方法参考 Java 使用内部 class

method reference Java using an inner class

public static class CompareClass {

    public static int  CompareBetweenStudents(Student student, Student othStudent) {
        return student.getNume().compareTo(othStudent.getNume());

    }

}

public List<Student> filterStudentsByLetter(String letter){

    Predicate<Student> predicate = x->x.getNume().indexOf(letter) == 0;
    Iterable<Student> list = getAllStudenti();
    Object[] objects = genericFilter(list, predicate, CompareClass::CompareBetweenStudents).toArray();
    return null;
}


public  <E> List<E> genericFilter(List<E> list, Predicate<E> predicate, Comparator<E> comp){
    return list.stream().filter(predicate).sorted(comp).collect(Collectors.toList());
}

我正在尝试制作一个可比较的 class 以在过滤器中使用,但我一直得到 CompareClass::CompareBetweenStudents 作为 "Cannot resolve methodCompareBetweenStudents"。我该如何解决?

genericFilter(list, predicate, CompareClass::CompareBetweenStudents) 中的参数类型与 genericFilter 的声明类型不匹配。

传递的list是一个Iterable<Student>, 但是 genericFilter 方法需要 List<Student>.

传递的 CompareClass::CompareBetweenStudents 不是 Comparator<Student>。要修复此参数, 您可以更改 CompareClass 的实现:

public static class CompareClass implements Comparator<Student> {
    @Override
    public int compare(Student student, Student othStudent) {
        return student.getNume().compareTo(othStudent.getNume());
    }
}

然后将new CompareClass()传递给genericFilter

你不需要为此实现 class(比较),你可以简单地做:

genericFilter(list, predicate, Comparator.comparing(x -> x.getName()))

不过还有一个问题:您将列表声明为 Iterable<Student> list,但将其作为 List<E> list 传递。那是行不通的,将 getAllStudenti() 修复为 return List<Student>

编辑:我发现了错误。 Genericfilter 得到一个列表,但我将一个可迭代对象作为参数传递。在我从 Iterable 改成 List 之后,它起作用了。

private <E> List<E> fromIterableToList(Iterable<E> iterableList){
    List<E> newList=new ArrayList<>();
    for(E e:iterableList){
        newList.add(e);
    }
    return newList;
}

我调用了函数:

genericFilter(fromIterableToList(list), predicate, CompareClass::CompareBetweenStudents);