How to pass function references to my method and use them?

I have a working method that I would like to make more general using lambdas or function references. That is, for some methods called in my method, I would like to specify them as arguments for my method. However, I can’t get it.

Let's say I have the following basic class structure

class B {}
class C {
    public Set<Integer> getIds() { ... }
    public void addB(B b) { ... }
}

And I have my working method

private void p1(Map<Integer, C> cs, Map<Integer, B> bs) {
    for (C c : cs.values()) {
        for (Integer id : c.getIds()) {
            if (bs.containsKey(id)) {
                c.addB(bs.get(id));
            }
        }
    }
}

What is called p1(cs, bs);so good.

The first step in making this more general is to provide a lambda for the method getIds(). I achieved this using:

private void p1(Map<Integer, C> cs, Map<Integer, B> bs, Function<C, Set<Integer>> f) {
    for (C c : cs.values()) {
        for (Integer id : f.apply(c)) {  // Change here
            if (bs.containsKey(id)) {
                c.addB(bs.get(id));
            }
        }
    }
}

What is called this: p1(cs, bs, C::getIds);- again, so good. Now I pass getIds()as an argument to my function and use it.

addB() p1(), . , . Function Consumer<B>, , . ?

+4
1

A BiConsumer<C,B> :

private void p1(Map<Integer, C> cs, Map<Integer, B> bs, Function<C, Set<Integer>> f, BiConsumer<C,B> cons) {
    for (C c : cs.values()) {
        for (Integer id : f.apply(c)) {
            if (bs.containsKey(id)) {
                cons.accept(c,bs.get(id));
            }
        }
    }
}

lambda (c,b)->c.addB(b) C::addB .

+5

Source: https://habr.com/ru/post/1695040/


All Articles