Created
November 6, 2017 14:19
-
-
Save bmaggi/842ecdedb2b36b469647240ad04acf7a to your computer and use it in GitHub Desktop.
A simple way to use predicate to filter data structure (also catch the exception)
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
import java.util.Arrays; | |
import java.util.List; | |
import java.util.function.Predicate; | |
import java.util.stream.Collectors; | |
/** | |
* A simple way to use predicate to filter data structure | |
* | |
* @author Benoit Maggi | |
* | |
*/ | |
public class NoGenericPredicateFilter { | |
public static final String[] dictionary = { "a", "ab", "ba", "c" }; | |
public static List<String> getMatchingWords(Predicate p){ | |
return (List<String>) Arrays.stream(dictionary).filter(o -> {try {return p.test(o);} catch (Exception e){return false;}}).collect(Collectors.toList()); | |
} | |
public static void main(String[] args) { | |
List<String> startWithA = getMatchingWords(new Predicate<String>() { | |
@Override | |
public boolean test(String string) { | |
return string.startsWith("a"); | |
} | |
}); | |
List<String> containsA = getMatchingWords(new Predicate<String>() { | |
@Override | |
public boolean test(String string) { | |
return string.contains("a"); | |
} | |
}); | |
List<String> empty = getMatchingWords(new Predicate<Integer>() { | |
@Override | |
public boolean test(Integer integer) { | |
return integer.intValue() > 5; | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment