Practice Programs on Stream Operations

1. Display All Elements Using Stream

This program demonstrates how to create a stream from a list. It displays all the elements using the forEach() stream operation.

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

public class DisplayElements {

    public static void main(String[] args) {

        List<String> fruits = Arrays.asList("Apple", "Banana", "Mango", "Orange");

        System.out.println("List Elements:");

        fruits.stream()
              .forEach(System.out::println);
    }
}
Output:
List Elements:
Apple
Banana
Mango
OrangeCode language: PHP (php)

2. Filter Even Numbers

This program filters even numbers from a list using the filter() operation. Only numbers divisible by 2 are displayed.

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

public class FilterEvenNumbers {

    public static void main(String[] args) {

        List<Integer> numbers = Arrays.asList(10, 15, 20, 25, 30, 35, 40);

        System.out.println("Even Numbers:");

        numbers.stream()
               .filter(n -> n % 2 == 0)
               .forEach(System.out::println);
    }
}
Output:
Even Numbers:
10
20
30
40

3. Filter Odd Numbers

This program filters odd numbers from a list using the filter() operation. Only numbers that are not divisible by 2 are displayed.

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

public class FilterOddNumbers {

    public static void main(String[] args) {

        List<Integer> numbers = Arrays.asList(10, 15, 20, 25, 30, 35, 40);

        System.out.println("Odd Numbers:");

        numbers.stream()
               .filter(n -> n % 2 != 0)
               .forEach(System.out::println);
    }
}
Output:
Odd Numbers:
15
25
35

4. Find Maximum Element

This program finds the largest element in a list using the max() stream operation. The maximum value is displayed on the console.

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

public class MaximumElement {

    public static void main(String[] args) {

        List<Integer> numbers = Arrays.asList(25, 40, 18, 90, 65);

        int max = numbers.stream()
                         .max(Integer::compare)
                         .get();

        System.out.println("Maximum Element = " + max);
    }
}
Output:
Maximum Element = 90

5. Find Minimum Element

This program finds the smallest element in a list using the min() stream operation.The minimum value is displayed on the console.

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

public class MinimumElement {

    public static void main(String[] args) {

        List<Integer> numbers = Arrays.asList(25, 40, 18, 90, 65);

        int min = numbers.stream()
                         .min(Integer::compare)
                         .get();

        System.out.println("Minimum Element = " + min);
    }
}
Output:
Minimum Element = 18

6. Sort Elements in Ascending Order

This program sorts the elements of a list in ascending order. It uses the sorted() stream operation to arrange the elements.

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

public class SortAscending {

    public static void main(String[] args) {

        List<Integer> numbers = Arrays.asList(45, 10, 35, 20, 15);

        System.out.println("Sorted Elements:");

        numbers.stream()
               .sorted()
               .forEach(System.out::println);
    }
}
Output:
Sorted Elements:
10
15
20
35
45

7. Sort Elements in Descending Order

This program sorts the elements of a list in descending order. It uses the sorted() operation with Comparator.reverseOrder().

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

public class SortDescending {

    public static void main(String[] args) {

        List<Integer> numbers = Arrays.asList(45, 10, 35, 20, 15);

        System.out.println("Descending Order:");

        numbers.stream()
               .sorted(Comparator.reverseOrder())
               .forEach(System.out::println);
    }
}
Output:
Descending Order:
45
35
20
15
10

8. Count Number of Elements

This program counts the total number of elements in a list. It uses the count() stream operation to determine the size.

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

public class CountElements {

    public static void main(String[] args) {

        List<String> names = Arrays.asList(
                "Rahul",
                "Priya",
                "Kiran",
                "Anil",
                "Sneha"
        );

        long count = names.stream().count();

        System.out.println("Number of Elements = " + count);
    }
}
Output:
Number of Elements = 5Code language: JavaScript (javascript)

9. Find Sum of Elements

This program calculates the sum of all numbers in a list. It uses the mapToInt() and sum() stream operations.

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

public class SumElements {

    public static void main(String[] args) {

        List<Integer> numbers = Arrays.asList(10, 20, 30, 40, 50);

        int sum = numbers.stream()
                         .mapToInt(Integer::intValue)
                         .sum();

        System.out.println("Sum = " + sum);
    }
}
Output:
Sum = 150

10. Find Average of Numbers

This program calculates the average of numbers in a list. It uses the average() stream operation to compute the mean value.

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

public class AverageNumbers {

    public static void main(String[] args) {

        List<Integer> numbers = Arrays.asList(10, 20, 30, 40, 50);

        OptionalDouble average = numbers.stream()
                                        .mapToInt(Integer::intValue)
                                        .average();

        if (average.isPresent()) {
            System.out.println("Average = " + average.getAsDouble());
        }
    }
}
Output:
Average = 30.0

11.Remove Duplicate Elements

This program removes duplicate elements from a list. It uses the distinct() stream operation to display unique values.

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

public class RemoveDuplicates {

    public static void main(String[] args) {

        List<Integer> numbers = Arrays.asList(10, 20, 10, 30, 20, 40, 50);

        System.out.println("Unique Elements:");

        numbers.stream()
               .distinct()
               .forEach(System.out::println);
    }
}
Output:
Unique Elements:
10
20
30
40
50

12. Find Square of Each Number

This program finds the square of every number in a list. It uses the map() stream operation to transform each element.

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

public class SquareNumbers {

    public static void main(String[] args) {

        List<Integer> numbers = Arrays.asList(2, 4, 6, 8, 10);

        System.out.println("Square of Numbers:");

        numbers.stream()
               .map(n -> n * n)
               .forEach(System.out::println);
    }
}
Output:
Square of Numbers:
4
16
36
64
100

13. Convert Strings to Uppercase

This program converts all strings in a list to uppercase. It uses the map() operation with the toUpperCase() method.

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

public class UpperCaseStrings {

    public static void main(String[] args) {

        List<String> names = Arrays.asList(
                "rahul",
                "priya",
                "anil",
                "kiran"
        );

        System.out.println("Uppercase Strings:");

        names.stream()
             .map(String::toUpperCase)
             .forEach(System.out::println);
    }
}
Output:
Uppercase Strings:
RAHUL
PRIYA
ANIL
KIRAN

14. Collect Stream Elements into a List

This program collects filtered elements into a new list. It uses the collect() operation along with Collectors.toList().

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class CollectList {

    public static void main(String[] args) {

        List<Integer> numbers = Arrays.asList(10, 15, 20, 25, 30);

        List<Integer> evenNumbers = numbers.stream()
                                           .filter(n -> n % 2 == 0)
                                           .collect(Collectors.toList());

        System.out.println("Even Numbers:");

        evenNumbers.forEach(System.out::println);
    }
}
Output:
Even Numbers:
10
20
30

15. Find First Element

This program finds the first element of a list. It uses the findFirst() stream operation.

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

public class FindFirstElement {

    public static void main(String[] args) {

        List<String> cities = Arrays.asList(
                "Hyderabad",
                "Chennai",
                "Delhi",
                "Mumbai"
        );

        Optional<String> city = cities.stream()
                                      .findFirst();

        if (city.isPresent()) {
            System.out.println("First Element = " + city.get());
        }
    }
}
Output:
First Element = Hyderabad

16. Match Operations (anyMatch(), allMatch(), noneMatch())

This program demonstrates the use of anyMatch(), allMatch(), and noneMatch() stream operations. These operations check whether elements satisfy a given condition.

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

public class MatchOperations {

    public static void main(String[] args) {

        List<Integer> numbers = Arrays.asList(10, 20, 30, 40, 50);

        boolean any = numbers.stream()
                             .anyMatch(n -> n > 40);

        boolean all = numbers.stream()
                             .allMatch(n -> n > 5);

        boolean none = numbers.stream()
                              .noneMatch(n -> n < 0);

        System.out.println("Any number greater than 40 : " + any);
        System.out.println("All numbers greater than 5 : " + all);
        System.out.println("No negative numbers : " + none);
    }
}
Output:
Any number greater than 40 : true
All numbers greater than 5 : true
No negative numbers : trueCode language: JavaScript (javascript)

17. Skip and Limit Elements

This program demonstrates the use of skip() and limit() stream operations. It skips the first two elements and displays the next three elements.

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

public class SkipLimit {

    public static void main(String[] args) {

        List<Integer> numbers = Arrays.asList(10, 20, 30, 40, 50, 60, 70);

        System.out.println("Result:");

        numbers.stream()
               .skip(2)
               .limit(3)
               .forEach(System.out::println);
    }
}
Output:
Result:
30
40
50

18. Group Students by Department

This program groups students based on their department. It uses the Collectors.groupingBy() operation to organize the data.

import java.util.*;
import java.util.stream.Collectors;

class Student {

    String name;
    String department;

    Student(String name, String department) {
        this.name = name;
        this.department = department;
    }
}

public class GroupByExample {

    public static void main(String[] args) {

        List<Student> students = Arrays.asList(
                new Student("Rahul", "CSE"),
                new Student("Priya", "ECE"),
                new Student("Anil", "CSE"),
                new Student("Sneha", "EEE")
        );

        Map<String, List<Student>> group =
                students.stream()
                        .collect(Collectors.groupingBy(s -> s.department));

        group.forEach((dept, list) -> {

            System.out.println(dept);

            list.forEach(s -> System.out.println(s.name));
        });
    }
}
Output:
CSE
Rahul
Anil
ECE
Priya
EEE
Sneha

19. Count Frequency of Elements

This program counts the frequency of each element in a list. It uses Collectors.groupingBy() along with Collectors.counting().

import java.util.*;
import java.util.stream.Collectors;

public class FrequencyCount {

    public static void main(String[] args) {

        List<String> fruits = Arrays.asList(
                "Apple",
                "Banana",
                "Apple",
                "Orange",
                "Banana",
                "Apple"
        );

        Map<String, Long> frequency = fruits.stream()
                .collect(Collectors.groupingBy(
                        fruit -> fruit,
                        Collectors.counting()));

        frequency.forEach((fruit, count) ->
                System.out.println(fruit + " : " + count));
    }
}
Output:
Apple : 3
Banana : 2
Orange : 1

20. Employee Stream Operations

This program filters employees with a salary greater than ₹50,000 and sorts them by salary. It demonstrates the use of filter(), sorted(), and forEach() stream operations.

import java.util.*;
import java.util.stream.Collectors;

class Employee {

    int id;
    String name;
    double salary;

    Employee(int id, String name, double salary) {
        this.id = id;
        this.name = name;
        this.salary = salary;
    }
}

public class EmployeeStream {

    public static void main(String[] args) {

        List<Employee> employees = Arrays.asList(
                new Employee(101, "Rahul", 45000),
                new Employee(102, "Priya", 65000),
                new Employee(103, "Anil", 55000),
                new Employee(104, "Sneha", 75000)
        );

        System.out.println("Employees with Salary > 50000");

        employees.stream()
                .filter(e -> e.salary > 50000)
                .sorted(Comparator.comparingDouble(e -> e.salary))
                .forEach(e ->
                        System.out.println(
                                e.id + " " +
                                e.name + " " +
                                e.salary));
    }
}
Output:
Employees with Salary > 50000
103 Anil 55000.0
102 Priya 65000.0
104 Sneha 75000.0Code language: CSS (css)
Scroll to Top