Guava의 Collections2 클래스에서 많이 사용되는 Collections2.filter() 예제이다.
직원들 중 퇴사자는 빼고 나머지만 보여주는 예제이다.
예제
import java.util.List;
import javax.annotation.Nullable;
import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.junit.Test;
import com.google.common.base.Predicate;
import com.google.common.collect.Collections2;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
public class GuavaTest {
@Test
public void test() {
ImmutableList<Member> list = ImmutableList.<Member>builder()
.add(new Member("Samuel", 1, false))
.add(new Member("Jason", 2, true))
.add(new Member("Daniel", 3, false))
.build();
List<Member> filteredList = Lists.newArrayList(Collections2.filter(list, new Predicate<Member>() {
@Override
public boolean apply(@Nullable Member member) {
return !member.isResigned;
}
}));
System.out.println(filteredList);
}
}
class Member {
String name;
int id;
boolean isResigned;
public Member(String name, int id, boolean isResigned) {
this.name = name;
this.id = id;
this.isResigned = isResigned;
}
@Override
public String toString() {
return ReflectionToStringBuilder.toString(this);
}
}
결과
[com.google.Member@74ee003d[name=Samuel,id=1,isResigned=false], com.google.Member@1d4455b3[name=Daniel,id=3,isResigned=false]]
'general java' 카테고리의 다른 글
[Guava] Preconditions 예제 (0) | 2015.04.16 |
---|---|
[Guava] CacheBuilder, CachLoader 예제 (0) | 2015.04.15 |
[Guava] Multimap 예제 (0) | 2015.04.11 |
[Guava] 자주 사용하는 Lists api (0) | 2015.04.10 |
[Guava] ImmutableMap, ImmutableSet, ImmutableList 예제 (0) | 2015.04.10 |