Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java equivalent to Python's itertools.groupby()?

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?

like image 912
Anthony Kong Avatar asked Jul 14 '11 04:07

Anthony Kong


People also ask

What does Python Itertools Groupby () do?

groupby() This method calculates the keys for each element present in iterable. It returns key and iterable of grouped items.

Can you Groupby for list Python?

In Python, you can group consecutive elements of the same value in an iterable object such as a list with itertools. groupby() .

What are Itertools in Python?

Itertools is a module in Python, it is used to iterate over data structures that can be stepped over using a for-loop. Such data structures are also known as iterables. This module works as a fast, memory-efficient tool that is used either by themselves or in combination to form iterator algebra.


1 Answers

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.

like image 191
Manuel Salvadores Avatar answered Sep 24 '22 17:09

Manuel Salvadores