lundi, avril 06, 2009

java list management and filtering without any loop (for, while)

Just a Java exercize for the fun of it: do some list manipulation / filtering without using for/while statements:

1 Have a list of people belonging to various countries:

European people: [Eric from France, Martine from France, John from Great-Britain, Martha from Great-Britain, Carine from France, Gerd from Deutschland, Giuseppe from Italia, Martha from Deutschland]

2 Get the different countries:

European countries: [Gerd from Deutschland, Eric from France, John from Great-Britain, Giuseppe from Italia]

3 List the people that belong to each country
:
People from: [France]: [Carine from France, Eric from France, Martine from France]
People from: [Deutschland]: [Gerd from Deutschland, Martha from Deutschland]
People from: [Great-Britain]: [John from Great-Britain, Martha from Great-Britain]
People from: [Italia]: [Giuseppe from Italia]

Never use for while statements to perform these tasks but make heavy use of the SortedSet type.
Find code here.

The trick is to use a compare function that return 0 when the guy's/lady's country does not match the country we are listing inhabitants for.

Read also the same exercize done differently in Java and Haskell:

1 commentaire:

Eric Mariacher a dit…

As I read today, by not using any for/while statement I was oding some kind of functional programming...

Read the same code in haskell (a real functional programming language).

http://eric-mariacher.blogspot.com/2010/04/java-vs-haskell.html