public class FluentIterableTest {
public static void main(String[] args) {
Man man1 = new Man("Jack Miller", 18);
Man man11 = new Man("Jack Miller", 18);
Man man2 = new Man("Roy Miller", 18);
Man man3 = new Man("Lily Miller", 11);
Man man4 = new Man("Rose Miller", 5);
Man man5 = new Man("Mike Chen", 34);
List<Man> manList = ImmutableList.of(man1, man11, man2, man3, man4, man5);
Set<Man> mans = FluentIterable.from(manList).toSet();
System.out.println(mans.size());
//转换
List<String> transformed = FluentIterable.from(manList).transform(new Function<Man, String>() {
@Override
public String apply(Man input) {
return Joiner.on('#').join(input.getName(), input.getAge());
}
}).toList();
System.out.println(transformed);
// 组合Predicate条件
Predicate<Man> predicate = Predicates.alwaysTrue();
predicate = Predicates.and(predicate, new NamePredicate("Chen"));
predicate = Predicates.and(predicate, new AgePredicate(15));
// 使用FluentIterable过滤元素,返回一个Iterable[]
Iterable<Man> manIterable = FluentIterable.from(manList).filter(predicate).limit(3)
.transform(new Function<Man, Man>() {
@Override
public Man apply(Man man) {
man.setAge(man.getAge() * 2);
return man;
}
});
System.out.println(manIterable);
}
}
class Man {
private String name;
private int age;
public Man(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return name + " is " + age + " years old";
}
}
class AgePredicate implements Predicate<Man> {
private int minAge;
public AgePredicate(int minAge) {
this.minAge = minAge;
}
@Override
public boolean apply(Man man) {
if (man.getAge() < minAge)
return false;
return true;
}
}
class NamePredicate implements Predicate<Man> {
private String illegalName;
public NamePredicate(String illegalName) {
this.illegalName = illegalName;
}
@Override
public boolean apply(Man man) {
if (man.getName().contains(illegalName))
return false;
return true;
}
}