Guava의 Collections2 클래스에서 많이 사용되는 Collections2.filter() 예제이다.

http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/collect/Collections2.html


직원들 중 퇴사자는 빼고 나머지만 보여주는 예제이다. 

예제


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]]


Posted by '김용환'
,