Skip to content

Instantly share code, notes, and snippets.

@Alos
Last active August 29, 2015 13:56
Show Gist options
  • Save Alos/8837265 to your computer and use it in GitHub Desktop.
Save Alos/8837265 to your computer and use it in GitHub Desktop.
Filter list in Java using Google Guava
package com.alos;
public class Dog {
private String name;
public Dog(String aName) {
this.name = aName;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package com.alos;
import java.util.regex.Pattern;
import com.google.common.base.Predicate;
public class DogFilter implements Predicate<Dog>{
private final Pattern pattern;
public DogFilter(final String regex){
this.pattern = Pattern.compile(regex);
}
@Override
public boolean apply(final Dog aDog) {
return pattern.matcher(aDog.getName()).find();
}
}
package com.alos;
import java.util.LinkedList;
import java.util.List;
import com.google.common.collect.Collections2;
import com.google.common.collect.Lists;
public class FilterTest {
public static void main(String arg[]){
Dog myDog1 = new Dog("Bob");
Dog myDog2 = new Dog("Bobby");
Dog myDog3 = new Dog("Fluffy");
Dog myDog4 = new Dog("Jack");
List<Dog> aListOfDogs = new LinkedList<Dog>();
aListOfDogs.add(myDog1);
aListOfDogs.add(myDog2);
aListOfDogs.add(myDog3);
aListOfDogs.add(myDog4);
List<Dog> filteredList = Lists.newArrayList(Collections2.filter(aListOfDogs, new DogFilter("^B")));
for(Dog aDog: filteredList)
System.out.println(aDog.getName());
}
}
Bob
Bobby
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment