如何在Jython中使用Java 8 lambdas

时间:2017-05-15 01:49:24

标签: jython jython-2.7

我试图在jython中试验java 8流和集合,看看它们在纯jython中实现时是否有效。它发生在我身上(任何评论也赞赏)

我从一些例子开始,计算

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()))

打印cnt作为字典     {u' a':2L,u' b':1L,u' c':1L}

到目前为止一切顺利。接下来,我找到了一个关于在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();

这将如何转化为jython。具体如何编写java lambda表达式,如string - &gt; jython中的sting.isEmpty()?

1 个答案:

答案 0 :(得分:1)

这里是一个在流上使用过滤器的示例,需要一个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将首先对Predicate进行子类化并实现测试方法。

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)

然后打印

数:

5L

LST:

[abc, bc, efg, abcd, jkl]