Search code examples
jythonjython-2.7

How to use Java 8 lambdas in Jython


I am trying to experiment with java 8 streams and collections in jython to see if they are any efficient then when implemented in pure jython. It occurs to me it could (any comments on this also appreciated)

I started with some examples, the counting

from java.util.function import Function
from java.util import ArrayList
from java.util.stream import Collectors

letters = ArrayList(['a','b','a','c']);

cnt=letters.stream().collect(Collectors.groupingBy(Function.identity(),
                                            Collectors.counting()))

printing cnt as dictionary {u'a': 2L, u'b': 1L, u'c': 1L}

so far so good. Next, I found a example on using filter on streams in java

List<String>strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
//get count of empty string
int count = strings.stream().filter(string -> string.isEmpty()).count();

how would this translate to in jython. specifically how can one write java lambda expression like string -> sting.isEmpty() in jython?


Solution

  • here is an example for using a filter on a stream need a object of type Predicate (java.util.function.Predicate)

    for java code:

    List<String>strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
    //get count of empty string
    int count = strings.stream().filter(string -> string.isEmpty()).count();
    

    eqvivalet jython would be to first subclassing Predicate and implementing a test method.

    from java.util.function import Predicate
    from java.util.stream import Collectors
    
    class pred(Predicate):
       def __init__(self,fn):
           self.test=fn
    
    @pred
    def mytest(s):
        from java.lang import String
        return not String(s).isEmpty() #or just use len(s.strip())==0
    
    strings = ArrayList(["abc", "", "bc", "efg", "abcd","", "jkl"])
    count = strings.stream().filter(mytest).count()
    lst=strings.stream().filter(mytest).collect(Collectors.toList())
    print(count)
    print(lst)
    

    then prints

    count:

    5L
    

    lst:

    [abc, bc, efg, abcd, jkl]