Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jython function to java Consumer

I want to give a python function as a Consumer for a java method.

public Class MyObject {
    public void javaFunction(Consumer<Double> consumer){...}
}

and

def python_function(arg):
    some_code_using(arg)

I tried the following:

myObjectInstance.javaFunction(python_function)

and

myObjectInstance.javaFunction(lambda arg: python_function(arg))

Each time, I get 1st arg can't be coerced to java.util.function.Consumer

I've done this before with Suppliers and it worked well. I'm using org.python.util.PythonInterpreter

Any ideas on how to pass such a Consumer ?

like image 820
ldebroux Avatar asked Nov 04 '25 07:11

ldebroux


1 Answers

Following hints from this answer by @suvy one could create set of helper classed like so

from java.util.Arrays import asList
from java.util.function import Predicate, Consumer, Function
from java.util.stream import Collectors

class jc(Consumer):
    def __init__(self, fn):
        self.accept=fn

class jf(Function):
    def __init__(self, fn):
        self.apply = fn

class jp(Predicate):
    def __init__(self, fn):
        self.test = fn

Which later could be used like so

>>> def p(x):
...     print(x)
... 
>>> asList("one", "two", "three").stream().filter(jp(lambda x: len(x)>3)).map(jf(lambda x: "a"+x)).forEach(jc(lambda x: p("foo"+x))).collect(Collectors.toList())
fooathree

or using built-in Collectors class, if you need collection as result

>>> asList("one", "two", "three").stream().filter(jp(lambda x: len(x)>3)).map(jf(lambda x: "a"+x)).collect(Collectors.toList())
[athree]
like image 141
ColdLearning Avatar answered Nov 06 '25 20:11

ColdLearning



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!