bogdanc
bogdanc

Reputation: 78

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());
}

I am trying to make a comparable class to use in a filter but I keep getting CompareClass::CompareBetweenStudents as "Cannot resolve methodCompareBetweenStudents". How can I solve it?

Upvotes: 1

Views: 894

Answers (3)

Nir Alfasi
Nir Alfasi

Reputation: 53525

You don't need to implement a class for that (comparing), you can simply do:

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

There's one other issue though: you declare list as Iterable<Student> list but pass it as a List<E> list. That's not going to work, fix getAllStudenti() to return List<Student>

Upvotes: 2

bogdanc
bogdanc

Reputation: 78

EDIT: I found the mistake. Genericfilter get's a List but I pass as argument an iterable. After I changed from Iterable to List, it worked.

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

And I called the function:

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

Upvotes: -1

janos
janos

Reputation: 124646

The types of the parameters in genericFilter(list, predicate, CompareClass::CompareBetweenStudents) don't match the declared types of genericFilter.

The passed list is an Iterable<Student>, but the genericFilter method expects List<Student>.

The passed CompareClass::CompareBetweenStudents is not a Comparator<Student>. To fix this parameter, you can change the implementation of CompareClass this:

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

And then pass new CompareClass() to genericFilter.

Upvotes: 1

Related Questions