Google collection Library で感動したのは、
com.google.common.base.Predicate
com.google.common.base.Function
com.google.common.collect.Collections2
である。
以下、サンプル、User Beanクラスに対して
import java.util.Date;
public class User{
private String name;
private Date entrydate;
private Integer point;
public User(String name,Date entrydate,int point){
this.name = name;
this.entrydate = entrydate;
this.point = point;
}
// getter と setterがあるとする
}
=======================================
SimpleDateFormat sf = new SimpleDateFormat("yyyy/MM/dd");
Set<User> userset = new TreeSet<User>(
new Comparator<User>(){
@Override public int compare(User u1,User u2){return u1.getEntrydate().compareTo(u2.getEntrydate()) >= 0 ? 1 : -1;}
}
);
//
userset.add(new User("aaa",sf.parse("2009/08/21"),10));
userset.add(new User("bbb",sf.parse("2009/08/11"),12));
userset.add(new User("ccc",sf.parse("2009/08/14"),18));
userset.add(new User("ddd",sf.parse("2009/08/25"),7));
userset.add(new User("eee",sf.parse("2009/08/12"),21));
// Collections2.filter で抽出
Collection<User> ua = Collections2.filter(userset
,new Predicate<User>(){
@Override
public boolean apply(User u){
return u.getPoint() > 10 ? true : false;
}
}
);
for(Iterator<User> it=ua.iterator();it.hasNext();){
User u = it.next();
System.out.println(u.getName()+"\t"+sf.format(u.getEntrydate())+"\t"+u.getPoint());
}
System.out.println("------------");
// Collections2.transform で、name を抽出
Collection<String> unames = Collections2.transform(ua
,new Function<User,String>(){
@Override
public String apply(User u){
return u.getName();
}
}
);
for(Iterator<String> it=unames.iterator();it.hasNext();){
System.out.println(it.next());
}
System.out.println("------------");
Collection<String> unames2 = Collections2.transform(
Collections2.filter(userset
,new Predicate<User>(){
@Override
public boolean apply(User u){
return u.getPoint() > 10 ? true : false;
}
}
)
,new Function<User,String>(){
@Override
public String apply(User u){
return u.getName();
}
}
);
for(Iterator<String> it=unames2.iterator();it.hasNext();){
System.out.println(it.next());
}