6

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() does above?

serge1peshcoff
  • 4,342
  • 11
  • 45
  • 76
Anthony Kong
  • 37,791
  • 46
  • 172
  • 304

2 Answers2

6

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.

Community
  • 1
  • 1
Manuel Salvadores
  • 16,287
  • 5
  • 37
  • 56
0

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?

Community
  • 1
  • 1
CDMP
  • 310
  • 4
  • 10