这是Python中 itertools.groupby() 的示例使用案例:

from itertools import groupby

Positions = [   ('AU', '1M', 1000),
                ('NZ', '1M', 1000),
                ('AU', '2M', 4000),
                ('AU', 'O/N', 4500),
                ('US', '1M', 2500),
           ]

FLD_COUNTRY = 0
FLD_CONSIDERATION = 2

Pos = sorted(Positions, key=lambda x: x[FLD_COUNTRY])
for country, pos in groupby(Pos, lambda x: x[FLD_COUNTRY]):
    print country, sum(p[FLD_CONSIDERATION] for p in pos)

# -> AU 9500
# -> NZ 1000
# -> US 2500

Java是否有任何行为或可以实现上面的itertools.groupby()的语言构造或库支持?

最佳答案

最接近的东西可能在Apache Functor中。看看Examples of Functors, Transformers, Predicates, and Closures in Java,您将在其中找到一个示例。

顺便说一句-不要期望看到类似Python的东西,这些东西是用2-3行代码实现的。 Java尚未被设计为具有良好功能的语言。它根本不像脚本语言那样包含很多语法糖。 Maybe in Java 8 will see more of these things coming together。这就是为什么Scala出现的原因see this question,我在某个时候做过,得到了很好的相关答案。如您所见,在我的问题中,在Python中实现递归函数比在Java中实现更好。 Java具有许多良好的功能,但是功能编程绝对不是其中之一。

10-07 19:22
查看更多