Last active
August 29, 2015 13:56
-
-
Save Alos/8837265 to your computer and use it in GitHub Desktop.
Filter list in Java using Google Guava
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Bob | |
Bobby |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment