In the previous lession, we have learnt how to use filters and collectors. In filter we have passed the condition to evaluate whether the object is eligible to be filtered or not. Code given below for reference and highlighted in bold.
public class NowJava8 { public static void main(String[] args) { List lines = Arrays.asList("abc", "xyz", "shiva"); List result = lines.stream()
.filter(line -> !"shiva".equals(line)).collect(Collectors.toList()); result.forEach(System.out::println); //output : abc,xyz } }
Now, what if I would like to same condition in different places to filter on different collections. We would end up repleating same piece of code.
What does it mean? we break DRY (Do not repeat yourself).
Here to solve this we can use predicates. Example given below.
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
public class PredicatesExample
{
public static Predicate<String> isShiva() {
return s -> s.equalsIgnoreCase("shiva");
}
public static void main(String[] args) {
List<String> lines = Arrays.asList("abc", "xyz", "shiva");
List<String> result = lines.stream()
.filter(isShiva().negate())
.collect(Collectors.toList());
result.forEach(System.out::println); //output : abc,xyz
List<String> names = Arrays.asList("abc", "dhdh", "shiva","ddds","edsd");
result =names.stream()
.filter(isShiva().negate())
.collect(Collectors.toList());
result.forEach(System.out::println); //output : abc,dhdh,ddds,edsd
}
}
As you see, we have used same predicate for two different collections.