Stream examples

1. Filter even numbers

List<Integer> nums = List.of(1, 2, 3, 4, 5, 6);

nums.stream()
    .filter(n -> n % 2 == 0)
    .forEach(System.out::println);

2. Convert list of strings to uppercase

List<String> names = List.of("ram", "shyam", "mohan");

List<String> result =
        names.stream()
             .map(String::toUpperCase)
             .toList();

3. Count elements greater than 50

List<Integer> marks = List.of(45, 60, 70, 30, 90);

long count =
        marks.stream()
             .filter(m -> m > 50)
             .count();

4. Remove duplicates

List<Integer> list = List.of(1, 2, 2, 3, 4, 4, 5);

List<Integer> unique =
        list.stream()
            .distinct()
            .toList();

5. Sort numbers

List<Integer> nums = List.of(5, 2, 8, 1);

List<Integer> sorted =
        nums.stream()
            .sorted()
            .toList();

6. Find first element

List<String> names = List.of("Aman", "Ravi", "Neha");

Optional<String> first =
        names.stream()
             .findFirst();

first.ifPresent(System.out::println);

7. Check if any element matches condition

List<Integer> nums = List.of(10, 20, 30);

boolean hasGreaterThan25 =
        nums.stream()
            .anyMatch(n -> n > 25);

8. Sum of numbers

List<Integer> nums = List.of(1, 2, 3, 4);

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

9. Group objects by property

class Employee {
    String dept;
    Employee(String dept) { this.dept = dept; }
    String getDept() { return dept; }
}

List<Employee> emps = List.of(
    new Employee("IT"),
    new Employee("HR"),
    new Employee("IT")
);

Map<String, List<Employee>> byDept =
        emps.stream()
            .collect(Collectors.groupingBy(Employee::getDept));

10. Find max element

List<Integer> nums = List.of(10, 40, 30);

Optional<Integer> max =
        nums.stream()
            .max(Integer::compareTo);

max.ifPresent(System.out::println);