Here is an example use case of itertools.groupby()
in Python:
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
Is there any language construct or library support in Java that behaves or can achieve what itertools.groupby()
doe开发者_开发问答s above?
The closest thing might be in Apache Functor. Have a look at Examples of Functors, Transformers, Predicates, and Closures in Java where you will find an example.
BTW - don't expect to see something like in Python, where these things are implemented in 2-3 lines of code. Java has not been designed as language with good functional features. It simply doesn't contain lots of syntactic sugar like scripting languages do. Maybe in Java 8 will see more of these things coming together. That is the reason why Scala came up, see this question that I made sometime ago where I got really good related answers. As you can see in my question implementing a recursive function is much nicer in Python than in Java. Java has lots of good features but definitely functional-programing is not one of them.
I had exactly the same question and found neoitertools: http://code.google.com/p/neoitertools/ via the answers to this question: Is there an equivalent of Python's itertools for Java?
精彩评论