Java 8 – Count Elements in a List

Introduction

Counting the number of elements in a list is a fundamental operation in programming. Whether you’re working with simple lists of numbers, strings, or complex objects, knowing how many elements are in your list is often essential. Java 8 introduced the Stream API, which makes this task more straightforward and allows for more complex counting operations in a functional style. This guide will show you how to count elements in a list using Java 8 Streams, covering basic counting as well as counting based on specific conditions.

Problem Statement

The task is to create a Java program that:

  • Accepts a list of elements.
  • Counts the total number of elements in the list.
  • Counts the number of elements that satisfy specific conditions.
  • Outputs the count.

Example 1:

  • Input: List of integers [1, 2, 3, 4, 5]
  • Output: 5

Example 2:

  • Input: List of strings ["apple", "banana", "orange", "mango"], count strings starting with “a”.
  • Output: 2

Solution Steps

  1. Input List: Start with a list of elements that can either be hardcoded or provided by the user.
  2. Count Elements Using Streams: Use the count() method to get the total number of elements or count elements that meet specific criteria.
  3. Display the Result: Print the count.

Java Program

Counting Total Elements in a List Using Streams

import java.util.Arrays;
import java.util.List;

/**
 * Java 8: Count Total Elements in a List Using Streams
 * Author: https://www.rameshfadatare.com/
 */
public class CountElementsInList {

    public static void main(String[] args) {
        // Step 1: Take input list
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

        // Step 2: Count the total number of elements in the list
        long count = numbers.stream().count();

        // Step 3: Display the result
        System.out.println("Total number of elements: " + count);
    }
}

Output

Total number of elements: 5

Explanation

In this example, the stream().count() method is used to count the total number of elements in the list numbers. The count() method returns the number of elements in the stream, which is then printed out. The result is 5, which is the total number of elements in the list.

Counting Elements Based on a Condition Using Streams

import java.util.Arrays;
import java.util.List;

/**
 * Java 8: Count Elements Based on a Condition in a List Using Streams
 * Author: https://www.rameshfadatare.com/
 */
public class CountElementsWithCondition {

    public static void main(String[] args) {
        // Step 1: Take input list
        List<String> fruits = Arrays.asList("apple", "banana", "orange", "mango");

        // Step 2: Count elements that start with 'a'
        long count = fruits.stream()
                           .filter(fruit -> fruit.startsWith("a"))
                           .count();

        // Step 3: Display the result
        System.out.println("Number of fruits starting with 'a': " + count);
    }
}

Output

Number of fruits starting with 'a': 2

Explanation

In this example, the filter() method is used to filter the stream of strings, keeping only those that start with the letter ‘a’. The count() method is then used to count the number of elements that satisfy this condition. The result is 2, as both "apple" and "banana" start with ‘a’.

Counting Elements in a List of Custom Objects Using Streams

import java.util.Arrays;
import java.util.List;

/**
 * Java 8: Count Elements in a List of Custom Objects Using Streams
 * Author: https://www.rameshfadatare.com/
 */
public class CountCustomObjectsInList {

    public static void main(String[] args) {
        // Step 1: Take input list of custom objects
        List<Student> students = Arrays.asList(
                new Student("Raj", 25),
                new Student("Anita", 30),
                new Student("Vikram", 22),
                new Student("Sita", 28)
        );

        // Step 2: Count students who are older than 25
        long count = students.stream()
                             .filter(student -> student.getAge() > 25)
                             .count();

        // Step 3: Display the result
        System.out.println("Number of students older than 25: " + count);
    }
}

// Custom class Student
class Student {
    private String name;
    private int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

Output

Number of students older than 25: 2

Explanation

In this example, the list of Student objects is filtered to count how many students are older than 25. The filter() method is used to apply the condition, and count() provides the number of matching elements. The result is 2, as both “Anita” and “Sita” are older than 25.

Advanced Considerations

  1. Counting Unique Elements: If you need to count unique elements in a list, you can use distinct() before count():
    long uniqueCount = list.stream().distinct().count();
    
  2. Performance Considerations: Counting elements using Streams is efficient for typical list sizes. For very large lists, consider using parallel streams (parallelStream()) to take advantage of multi-core processors.
  3. Combining Conditions: You can combine multiple conditions using logical operators within the filter() method to perform more complex counting operations.

Conclusion

This guide provides methods for counting elements in a list using Java 8 Streams, covering basic counting, counting based on conditions, and counting in lists of custom objects. Java 8 Streams offer a powerful and concise way to count elements, making your code more readable and maintainable. Depending on your specific use case, you can easily apply the counting techniques demonstrated in this guide to achieve the desired result.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top