In Java 8 , you may notice here and there some new interfaces popping out making us so unfamilar with. Well , Don't be panic. Actually, they are just some normal java syntaxs we learned before with a new name. In this article , I will tell one interface called predicate<T>.
Predicate is just a java interface with one method with return type "boolean". That's it . So , do we really need it in java api rather than we just randomly create a interface with one method with return type "boolean". Yes, we can , we don't need it at all in java api ,but since java api helps us creating one . So we just use it.
public interface Predicate<T> { boolean test(T t); }
So what is it used for ?
Well, it help us to filter some result based on the Class. Let's see an example below.
public class MainMethod { public static void main(String[] args) {
// filter the result == 123
List<String> result123 = filter(new ArrayList<String>(),
(String input) -> input.equals("123"));
} public static List<String> filter(List<String> list, Predicate<String> filter) { List<String> result = new ArrayList<>(); for(String item: list) { if( filter.test(item) ) { result.add(item); } } return result; } }
This program filter those results with a (String == 123). So we can call filter(...) function with one paramter called Predicate, then we specify the filter criteria when we call this function.
Alright , That's so simple to use. Well you may wonder why do we need predicate here rather than use boolean to write this function like filter (List<String> list, boolean filter) ?
Because predicate is to filter & judge a Class's field not just a simple field :
public static void main(String[] args) { List<Apple> result123 = filter(new ArrayList<Apple>(),
(Apple input) -> input.weight() > 100);
List<Apple> result123 = filter(new ArrayList<Apple>(),
(Apple input) -> input.color().contain("red")); } public static List<String> filter(List<Apple> list, Predicate<Apple> filter) { List<Apple> result = new ArrayList<>(); for(String item: list) { if( filter.test(item) ) { result.add(item); } } return result; }
Moreover, it is more readable for you as well if you use predicate<Apple> .
No comments:
Post a Comment