Learn Java 8 streams with an example - count() and filter() method
Example 1: Counting Empty String
import java.util.*;
import java.util.stream.Collectors;
/*Counting Empty String*/
public class DriverClass {
public static void main(String[] args) {
List<String> list = Arrays.asList("ss","","ss","","");
long count = list.stream().filter(o -> o.isEmpty()).count();
System.out.println(count);
}
}
Example 2: Count number of String which ends with "d"
import java.util.*;
/*Count number of String which ends with "d"*/
public class DriverClass {
public static void main(String[] args) {
List<String> list = Arrays.
asList("method", "static", "void", "abstract", "ping");
long count = list.stream().filter(x -> x.endsWith("d")).count();
System.out.println(count);
}
}
Example 3: Count number of Odd numbers
import java.util.*;
/*Count number of Odd numbers*/
public class DriverClass {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(1, 4, 6, 7, 9, 11);
long count = list.stream().filter(x -> x%2!=0).count();
System.out.println(count);
}
}
Example 4: Count String whose length is more than 3 characters
import java.util.*;
/*Count String whose length is more than 3 characters*/
public class DriverClass {
public static void main(String[] args) {
List<String> list = Arrays.
asList("saw", "wrong turn", "walking dead", "nun","jurassic park");
long count = list.stream().filter(x -> x.length()> 3).count();
System.out.println(count);
}
}
More Topics...