Forum Stats

  • 3,872,061 Users
  • 2,266,374 Discussions
  • 7,911,043 Comments

Discussions

Method reference does not work with the Decorator pattern

Denis.Makarskiy
Denis.Makarskiy Member Posts: 2
edited Apr 8, 2014 1:31PM in Java 8 Questions

Hello all!

I faced with a problem, when I use method reference as a function in Collectors.groupingBy I get an error: "no suitable method found for collect". But! if I replaced method reference with a lambda expression everything works fine.

Here is the code sample:

interface Iface{
    public int getPropertyOfClassA();
    public void setPropertyOfClassA(int propertyOfClassA);
}

class A implements Iface{
    private int propertyOfClassA;

    @Override
    public int getPropertyOfClassA() {
        return propertyOfClassA;
    }

    @Override
    public void setPropertyOfClassA(int propertyOfClassA) {
        this.propertyOfClassA = propertyOfClassA;
    }
}

class B{
    private A objectA;

    public int getPropertyOfClassA() {return objectA.getPropertyOfClassA();}
}

class C extends B {
    int propertyOfClassC;

    public int getPropertyOfClassC() {
        return propertyOfClassC;
    }

    public void setPropertyOfClassC(int propertyOfClassC) {
        this.propertyOfClassC = propertyOfClassC;
    }
}

public class example {
    public static void main(String[] ars){
        List<B> listOfB = new ArrayList<>();

        Map<Integer, List<B>> groupedByPropertyOfClassA = listOfB
                .stream()
                .collect(Collectors.groupingBy(C::getPropertyOfClassA));
    }

}


Change "C::getPropertyOfClassA" with "objC -> objC.getPropertyOfClassA()" and it works!

Any ideas?

Best Answer

  • James_D
    James_D Member Posts: 1,496 Gold Trophy
    Answer ✓

    You have a Stream<B>. Not every B is a C, so you can't apply a method of C to each element (even though that method is defined in B).

    It also works if you change it to

    collect(Collectors.groupingBy(B::getPropertyOfClassA));
    

Answers