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...

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Spring boot video streaming example-HTML5

Spring Boot + Mockito simple application with 100% code coverage

Spring Boot + OpenCSV Export Data to CSV Example

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Custom Exception Handling in Quarkus REST API

ReactJS, Spring Boot JWT Authentication Example

DataTable-Pagination example with Spring boot, jQuery and ajax

Spring Webflux File Download Example

Node JS mini projects with source code - free download