Lets say we have collection of strings and we would like to filter (remove) out certain strings from collection. We could achive the same in java 7 and earlier versions
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class BeforeJava8 {
public static void main(String[] args) {
List lines = Arrays.asList("abc","shiva", "xyz");
List result = getFilterOutput(lines, "shiva");
for (String temp : result) {
System.out.println(temp); //output : abc, xyz
}
}
private static List getFilterOutput(List lines, String filter) {
List result = new ArrayList<>();
for (String line : lines) {
if (!"shiva".equals(line)) {
result.add(line);
}
}
return result;
}
}
The same can be achieved in java 8.
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
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
}
}
So, what have we done here, we have used java 8 for filtering the collections and using lambda and reduced the number of lines to do the same.