Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Interested in getting your voice heard by members of the Developer Marketing team at Oracle? Check out this post for AppDev or this post for AI focus group information.

Method reference does not work with the Decorator pattern

Denis.MakarskiyMar 28 2014 — edited Apr 8 2014

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?

This post has been answered by James_D on Mar 28 2014
Jump to Answer

Comments

Post Details

Added on Mar 28 2014
2 comments
1,523 views