A while ago I wrote a program in Java doing some filtering and displaying without using for while statements and an other one using haskell functional language.
Today, I did the same thing (i.e. no for or while statements), but using lambdaj java library.
There is still a for statement but if you make country as an object and not a string then you can use lambdaj features.
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: [Great-Britain, France, Italia, Deutschland]
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]
Here is the code:
1 import static ch.lambdaj.Lambda.*;
2 import ch.lambdaj.group.*;
3 import java.util.List;
4 import java.util.Arrays;
5 import java.util.Set;
6
7
8 public class Europeans1 {
9
10 static List<People> l_europeans = Arrays.asList(
11 new People("Eric", "France"),
12 new People("Martine", "France"),
13 new People("John", "Great-Britain"),
14 new People("Martha", "Great-Britain"),
15 new People("Carine", "France"),
16 new People("Gerd", "Deutschland"),
17 new People("Giuseppe", "Italia"),
18 new People("Martha", "Deutschland"));
19
20 public static void main(String[] args) {
21 System.out.println("European people: "+l_europeans);
22 Group<People> g_countries = Groups.group(l_europeans,
23 Groups.by(on(People.class).getNationality()));
24 Set<String> set_countries = g_countries.keySet();
25 System.out.println("European countries: "+set_countries);
26 for(String s_country:set_countries) {
27 print_inhabitants(s_country);
28 }
29 }
30
31 static void print_inhabitants(String s_country) {
32 System.out.print("People from "+s_country+": ");
33 List<People> l_inhabitants = select(l_europeans,
34 having(on(People.class).getNationality(),
35 org.hamcrest.Matchers.equalTo(s_country)));
36 forEach(l_inhabitants).printFirstName();
37 System.out.println("");
38 }
39 }
2 commentaires:
Can the loop in your code be eliminated also using lambdaj?
There is still a for statement but if you make country as an object and not a string then you can use lambdaj features.
get_Nationality() would return a country_object and then we could write:
foreach(set_countries).print_inhabitants();
Enregistrer un commentaire