Guava의 Predicate과 Filter를 이용하여

List에서 Member의 특정 필드의 값이 false이면 , List에서 제외하는 예시이다.

package com.google;

import com.google.common.base.Predicate;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import org.apache.commons.lang.BooleanUtils;
import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.junit.Test;

import java.util.List;

public class GuavaFilterTest {

@Test
public void PredicateTest() {
List<Member> members = ImmutableList.<Member>builder()
.add(new Member("1", "true"))
.add(new Member("2", "true"))
.add(new Member("3", "false"))
.build();

Predicate<Member> predicate = new Predicate<Member>() {
@Override
public boolean apply(Member input) {
return BooleanUtils.toBoolean(input.followable);
}
};

List<Member> newMembers = FluentIterable.from(members).filter(predicate).toList();
System.out.println(newMembers);
}

@Test
public void PredicateTestWithJava8() {
List<Member> members = ImmutableList.<Member>builder()
.add(new Member("1", "true"))
.add(new Member("2", "true"))
.add(new Member("3", "false"))
.build();

List<Member> newMembers = FluentIterable.from(members)             .filter(s -> BooleanUtils.toBoolean(s.followable)).toList();
System.out.println(newMembers);
}

class Member {
public String id;
public String followable;

public Member(String id, String f) {
this.id = id;
this.followable = f;
}

public String toString() {
return ReflectionToStringBuilder.toString(this);
}
}
}


결과


[com.google.IterableTest$Member@3b81a1bc[id=1,followable=true], com.google.IterableTest$Member@13fee20c[id=2,followable=true]]

[com.google.IterableTest$Member@32d992b2[id=1,followable=true], com.google.IterableTest$Member@215be6bb[id=2,followable=true]]


Posted by '김용환'
,