Java7의 Guava의 FluentIterable 과 Java8의 Guava의 FluentIterable 를 비교해서 코딩했다. 




import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.Lists;
import org.junit.Before;
import org.junit.Test;

import java.util.List;

import static org.junit.Assert.assertEquals;

public class GuavaTest {

List<Person> persons = Lists.newArrayList();

@Before
public void before() {
Person samuel = new Person(10, "Samuel");
Person jason = new Person(25, "Jason");
Person kelly = new Person(21, "Kelly");

persons.add(samuel);
persons.add(jason);
persons.add(kelly);
}

@Test
public void simpleGuavaWithJava7() {
List<String> names = FluentIterable.from(persons)
.filter(new Predicate<Person>() {
@Override
public boolean apply(Person person) {
return person.age() >= 20;
}
})
.transform(new Function<Person, String>() {
@Override
public String apply(Person person) {
return person.name();
}
})
.toList();

assertEquals("Jason", names.get(0));
assertEquals("Kelly", names.get(1));
assertEquals(2, names.size());
}

@Test
public void simpleGuavaWithJava8() {
List<String> names = FluentIterable.from(persons)
.filter(person -> person.age() >= 20)
.transform(person -> person.name())
.toList();

assertEquals("Jason", names.get(0));
assertEquals("Kelly", names.get(1));
assertEquals(2, names.size());
}
}

class Person {
int age;
String name;

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

public int age() {
return age;
}

public String name() {
return name;
}

}




Posted by '김용환'
,