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

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete