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());
}
我试图在过滤器中使用类似的类,但我一直将CompareClass :: CompareBetweenStudents作为“无法解析methodCompareBetweenStudents”。我该如何解决?
答案 0 :(得分:2)
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
。
答案 1 :(得分:2)
你不需要为此实现一个类(比较),你可以这样做:
genericFilter(list, predicate, Comparator.comparing(x -> x.getName()))
还有另外一个问题:您将列表声明为Iterable<Student> list
,但将其作为List<E> list
传递。这不起作用,修复getAllStudenti()
以返回List<Student>
答案 2 :(得分:-1)
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);