Java 8 Collectors.counting() Example

Collectors.counting() is a simple collector that allows simply counting of all Stream elements.
Learn Java 8 at https://www.javaguides.net/p/java-8.html

Java 8 Collectors.counting() Example

import java.util.stream.Collectors;
import java.util.List;
import java.util.ArrayList;
class Product {
    int id;
    String name;
    float price;

    public Product(int id, String name, float price) {
        this.id = id;
        this.name = name;
        this.price = price;
    }
    public int getId() {
        return id;
    }
    public String getName() {
        return name;
    }
    public float getPrice() {
        return price;
    }
}
public class CollectorsExample {
    public static void main(String[] args) {
        List < Product > productsList = new ArrayList < Product > ();
        //Adding Products  
        productsList.add(new Product(1, "HP Laptop", 25000 f));
        productsList.add(new Product(2, "Dell Laptop", 30000 f));
        productsList.add(new Product(3, "Lenevo Laptop", 28000 f));
        productsList.add(new Product(4, "Sony Laptop", 28000 f));
        productsList.add(new Product(5, "Apple Laptop", 90000 f));
        Long noOfElements = productsList.stream()
            .collect(Collectors.counting());
        System.out.println("Total elements : " + noOfElements);
    }
}
Output:
Total elements : 5

 Java 8 Tutorials and Examples



Comments