lvjian700
2/7/2015 - 8:32 AM

Java Lambda with lambdaj and Java 8. https://code.google.com/p/lambdaj/wiki/LambdajFeatures

Java Lambda with lambdaj and Java 8. https://code.google.com/p/lambdaj/wiki/LambdajFeatures

package lambda;

import java.util.function.Function;

public class Person {
    private final String lastName;
    private final String firstName;
    private final int age;

    public Person(String firstName, String lastName, int age) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
    }

    public String getLastName() {
        return lastName;
    }

    public String getFirstName() {
        return firstName;
    }

    public int getAge() {
        return age;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Person person = (Person) o;

        if (age != person.age) return false;
        if (firstName != null ? !firstName.equals(person.firstName) : person.firstName != null) return false;
        if (lastName != null ? !lastName.equals(person.lastName) : person.lastName != null) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = lastName != null ? lastName.hashCode() : 0;
        result = 31 * result + (firstName != null ? firstName.hashCode() : 0);
        result = 31 * result + age;
        return result;
    }

    public String print(Function<Person, String> printFunction) {
        return printFunction.apply(this);
    }
}
package lambda;

import ch.lambdaj.function.convert.PropertyExtractor;
import ch.lambdaj.group.Group;
import org.junit.Test;

import java.util.List;
import java.util.Map;

import static ch.lambdaj.Lambda.*;
import static java.util.Arrays.asList;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;

public class LambdaTest {

    private List<Person> meAndMyFriends;
    private final Person me;
    private final Person luca;
    private final Person biagio;
    private final Person celestino;

    public LambdaTest() {
        me = new Person("Mario", "Fusco", 35);
        luca = new Person("Luca", "Marrocco", 29);
        biagio = new Person("Biagio", "Beatrice", 39);
        celestino = new Person("Celestino", "Bellone", 29);
        meAndMyFriends = asList(me, luca, biagio, celestino);
    }

    @Test
    public void should_filter_collections() {
        List<Integer> biggerThan3 = filter(greaterThan(3), asList(1, 2, 3, 4, 5));
        assertThat(biggerThan3, is(equalTo(asList(4,5))));

        List<Person> oldFriends = filter(
                having(on(Person.class).getAge(), greaterThan(30)),
                meAndMyFriends);
        assertThat(oldFriends, is(equalTo(asList(me, biagio))));
    }

    @Test
    public void should_select_one_from_collection() {
        Person person = selectUnique(meAndMyFriends,
                having(on(Person.class).getAge(), is(39)));
        assertThat(person, is(equalTo(biagio)));
    }

    @Test
    public void should_aggregate_values() {
        int sum = sum(asList(1, 2, 3, 4, 5)).intValue();
        assertThat(sum, is(15));

        int totalAge = sum(meAndMyFriends, on(Person.class).getAge());
        assertThat(totalAge, is(132));

        // curry sum
        totalAge = sumFrom(meAndMyFriends).getAge();
        assertThat(totalAge, is(132));
    }

    @Test
    public void should_join_values() {
        String friendNames = joinFrom(meAndMyFriends).getFirstName();
        assertThat(friendNames, is("Mario, Luca, Biagio, Celestino"));
    }

    @Test
    public void should_convert_index_sort_items() {
        List<Integer> lengths = convert(new String[] {
                "1","22","333"
        }, new PropertyExtractor("length"));

        assertThat(lengths, is(equalTo(asList(1,2,3))));

        List<Integer> ages = extract(meAndMyFriends, on(Person.class).getAge());
        assertThat(ages, is(equalTo(asList(35, 29, 39, 29))));

        Map<String, Person> personsByName = index(meAndMyFriends, on(Person.class).getFirstName());
        assertThat(personsByName.get("Mario"), is(me));

        List<Person> sorted = sort(meAndMyFriends, on(Person.class).getAge());
        assertThat(sorted.get(0), is(luca));
    }

    @Test
    public void should_grouping_items() {
        Group<Person> group29Age = group(meAndMyFriends,
                by(on(Person.class).getAge()));
        assertThat(group29Age.findGroup("29").getSize(), is(2));

        Group<Person> group = group(meAndMyFriends,
                by(on(Person.class).getAge()),
                by(on(Person.class).getFirstName()));

        Group<Person> group29aged = group.findGroup("29");
        Group<Person> group29agedNamedLuca = group29aged.findGroup("Luca");
        assertThat(group29agedNamedLuca.first(), is(luca));
    }

}
package lambda;

import org.junit.Test;

import java.util.List;
import java.util.function.Predicate;

import static java.lang.String.format;
import static java.util.Arrays.asList;
import static java.util.Collections.sort;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;

public class Java8FeatureTest {

    private List<Person> meAndMyFriends;
    private final Person me;
    private final Person luca;
    private final Person biagio;
    private final Person celestino;

    public Java8FeatureTest() {
        me = new Person("Mario", "Fusco", 35);
        luca = new Person("Luca", "Marrocco", 29);
        biagio = new Person("Biagio", "Beatrice", 39);
        celestino = new Person("Celestino", "Bellone", 29);
        meAndMyFriends = asList(me, luca, biagio, celestino);
    }

    @Test
    public void should_use_lambda_replace_function_interface() {

        sort(meAndMyFriends, (Person p1, Person p2) ->
                p1.getFirstName().compareTo(p2.getFirstName()));
        assertThat(meAndMyFriends, is(asList(biagio, celestino, luca, me)));
    }

    @Test
    public void should_use_predicate_test_object() {
        System.out.println("Call person if age < 30");
        callYonger(meAndMyFriends, (Person p) -> p.getAge() < 30);
    }

    @Test
    public void should_use_function_apply_to_object() {

        assertThat(me.print(p ->
                        format("%s.%s, %d", p.getFirstName(),
                                p.getLastName(), p.getAge())),
                is("Mario.Fusco, 35"));
    }

    @Test
    public void should_extract_age_using_map() {
        int[] ages = meAndMyFriends.stream()
                .mapToInt(p -> p.getAge())
                .sorted()
                .toArray();
        assertThat(ages, is(new int[] {29, 29, 35, 39}));
    }

    @Test
    public void should_calculate_age_using_map_reduce() {
        int sum = meAndMyFriends.stream()
                .mapToInt(p -> p.getAge())
                .reduce(0, (previous, current) -> previous + current);
        assertThat(sum, is(132));
    }

    @Test
    public void should_use_stream_api_in_collection() {
        System.out.println("The age > 30: ");
        meAndMyFriends.stream().filter((Person p) -> p.getAge() > 30)
                .forEach((Person p) -> System.out.println(p.getAge()));
    }

    private void callYonger(List<Person> meAndMyFriends, Predicate<Person> personPredicate) {
        meAndMyFriends.stream().forEach((Person p) -> {
            if(personPredicate.test(p)) {
                System.out.println(format("call: %s", p.getFirstName()));
            }
        });
    }
}