Wednesday, November 18, 2026

Java Stream API Complete Guide – List, Set, and Map Examples

Java Stream API Complete Guide – List, Set, and Map Examples

The Java Stream API was introduced in Java 8. It provides a functional programming approach to process collections such as List, Set, and Map.

Using Streams, we can perform operations such as:

  • Filtering elements.
  • Sorting elements in ascending and descending order.
  • Mapping and transforming data.
  • Grouping and partitioning elements.
  • Finding minimum and maximum values.
  • Removing duplicate elements.
  • Calculating sum, average, count, and statistics.
  • Converting List to Set, Set to List, and Map to List.
  • Grouping employees by department or salary.
  • Finding duplicate elements.
Java Stream API Complete Guide – List, Set, and Map Examples


1. Understanding Java Stream API

A Stream pipeline generally consists of three parts:

  1. Source: List, Set, Map, or Array.
  2. Intermediate Operations: filter(), map(), sorted(), distinct().
  3. Terminal Operations: collect(), forEach(), count(), reduce().

Basic Syntax


collection.stream()
    .filter(element -> condition)
    .map(element -> transformation)
    .sorted()
    .collect(Collectors.toList());
    

Intermediate vs Terminal Operations

Intermediate Operations Terminal Operations
filter()collect()
map()forEach()
flatMap()count()
sorted()reduce()
distinct()min()
limit()max()
skip()findFirst()
peek()anyMatch()
mapToInt()allMatch()

Intermediate operations are lazy. They execute when a terminal operation is invoked.

2. Java Stream API Imports


import java.util.*;
import java.util.stream.*;
import java.util.function.*;
    

3. Employee Class for Examples


class Employee {

    private int empID;
    private String empName;
    private String department;
    private double salary;

    public Employee(int empID, String empName,
                    String department, double salary) {
        this.empID = empID;
        this.empName = empName;
        this.department = department;
        this.salary = salary;
    }

    public int getEmpID() {
        return empID;
    }

    public String getEmpName() {
        return empName;
    }

    public String getDepartment() {
        return department;
    }

    public double getSalary() {
        return salary;
    }

    @Override
    public String toString() {
        return empID + " " + empName + " "
                + department + " " + salary;
    }
}
    

Create Employee Data


List<Employee> employees = Arrays.asList(

    new Employee(101, "Sumit", "QA", 75000),
    new Employee(102, "Rahul", "Dev", 85000),
    new Employee(103, "Amit", "QA", 65000),
    new Employee(104, "Priya", "Dev", 95000),
    new Employee(105, "Neha", "HR", 55000),
    new Employee(106, "Raj", "HR", 60000),
    new Employee(107, "John", "Dev", 90000),
    new Employee(108, "Ankit", "QA", 80000)
);
    

Part 1: Java Streams with List

4. Create a Stream from List


List<String> names = Arrays.asList(
    "Sumit", "Rahul", "Amit", "Priya"
);

Stream<String> stream = names.stream();

stream.forEach(System.out::println);
    

5. filter() – Filter Elements

Filter employees whose salary is greater than 75000.


List<Employee> result = employees.stream()
    .filter(e -> e.getSalary() > 75000)
    .collect(Collectors.toList());
    

Filter employees belonging to QA department:


List<Employee> result = employees.stream()
    .filter(e -> e.getDepartment().equals("QA"))
    .collect(Collectors.toList());
    

Filter employees whose name starts with S:


List<Employee> result = employees.stream()
    .filter(e -> e.getEmpName().startsWith("S"))
    .collect(Collectors.toList());
    

6. map() – Transform Elements

Extract employee names:


List<String> names = employees.stream()
    .map(Employee::getEmpName)
    .collect(Collectors.toList());
    

Extract employee salaries:


List<Double> salaries = employees.stream()
    .map(Employee::getSalary)
    .collect(Collectors.toList());
    

Convert names to uppercase:


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

7. sorted() – Sorting Elements

Sort employees by employee ID in ascending order.


List<Employee> result = employees.stream()
    .sorted(Comparator.comparingInt(Employee::getEmpID))
    .collect(Collectors.toList());
    

Sort employees by employee ID in descending order.


List<Employee> result = employees.stream()
    .sorted(Comparator.comparingInt(Employee::getEmpID).reversed())
    .collect(Collectors.toList());
    

Sort employees by employee name in ascending order.


List<Employee> result = employees.stream()
    .sorted(Comparator.comparing(Employee::getEmpName))
    .collect(Collectors.toList());
    

Sort employees by employee name in descending order.


List<Employee> result = employees.stream()
    .sorted(Comparator.comparing(Employee::getEmpName).reversed())
    .collect(Collectors.toList());
    

Sort employees by salary in ascending order.


List<Employee> result = employees.stream()
    .sorted(Comparator.comparingDouble(Employee::getSalary))
    .collect(Collectors.toList());
    

Sort employees by salary in descending order.


List<Employee> result = employees.stream()
    .sorted(Comparator.comparingDouble(Employee::getSalary).reversed())
    .collect(Collectors.toList());
    

8. distinct() – Remove Duplicate Elements


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

List<Integer> result = numbers.stream()
    .distinct()
    .collect(Collectors.toList());

System.out.println(result);
    

Output:

[10, 20, 30, 40, 50]

For custom objects, distinct() uses equals() and hashCode() to determine duplicates.

9. limit() and skip()

Get the first three employees:


List<Employee> result = employees.stream()
    .limit(3)
    .collect(Collectors.toList());
    

Skip the first three employees:


List<Employee> result = employees.stream()
    .skip(3)
    .collect(Collectors.toList());
    

Get the top three highest-paid employees:


List<Employee> result = employees.stream()
    .sorted(
        Comparator.comparingDouble(Employee::getSalary).reversed()
    )
    .limit(3)
    .collect(Collectors.toList());
    

10. forEach() – Iterate Elements


employees.stream()
    .forEach(e -> System.out.println(e.getEmpName()));
    

Using method reference:


employees.stream()
    .forEach(System.out::println);
    

11. count() – Count Elements


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

long filteredCount = employees.stream()
    .filter(e -> e.getSalary() > 75000)
    .count();
    

12. min() and max()

Find employee with minimum salary:


Optional<Employee> min = employees.stream()
    .min(Comparator.comparingDouble(Employee::getSalary));
    

Find employee with maximum salary:


Optional<Employee> max = employees.stream()
    .max(Comparator.comparingDouble(Employee::getSalary));
    

Get the highest salary:


double maxSalary = employees.stream()
    .mapToDouble(Employee::getSalary)
    .max()
    .orElse(0);
    

13. findFirst() and findAny()


Optional<Employee> first = employees.stream()
    .filter(e -> e.getSalary() > 75000)
    .findFirst();

Optional<Employee> any = employees.stream()
    .filter(e -> e.getDepartment().equals("QA"))
    .findAny();
    

findAny() does not guarantee which matching element is returned, especially with parallel streams.

14. anyMatch(), allMatch(), noneMatch()


// Check whether any employee earns more than 100000
boolean any = employees.stream()
    .anyMatch(e -> e.getSalary() > 100000);

// Check whether all employees earn more than 50000
boolean all = employees.stream()
    .allMatch(e -> e.getSalary() > 50000);

// Check whether no employee belongs to IT
boolean none = employees.stream()
    .noneMatch(e -> e.getDepartment().equals("IT"));
    

15. reduce() – Reduce Elements to a Single Result

Calculate the sum of numbers:


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

int sum = numbers.stream()
    .reduce(0, Integer::sum);

System.out.println(sum);
    

Output:

100

Calculate the product:


int product = numbers.stream()
    .reduce(1, (a, b) -> a * b);
    

Calculate total employee salary:


double totalSalary = employees.stream()
    .map(Employee::getSalary)
    .reduce(0.0, Double::sum);
    

16. mapToInt(), mapToDouble(), mapToLong()


// Total salary
double totalSalary = employees.stream()
    .mapToDouble(Employee::getSalary)
    .sum();

// Average salary
double averageSalary = employees.stream()
    .mapToDouble(Employee::getSalary)
    .average()
    .orElse(0);

// Minimum salary
double minSalary = employees.stream()
    .mapToDouble(Employee::getSalary)
    .min()
    .orElse(0);

// Maximum salary
double maxSalary = employees.stream()
    .mapToDouble(Employee::getSalary)
    .max()
    .orElse(0);
    

17. Collectors.toList() and Collectors.toSet()


// Stream to List
List<String> result = employees.stream()
    .map(Employee::getEmpName)
    .collect(Collectors.toList());

// Stream to Set
Set<String> departments = employees.stream()
    .map(Employee::getDepartment)
    .collect(Collectors.toSet());

// Modern Java
List<String> names = employees.stream()
    .map(Employee::getEmpName)
    .toList();
    

Stream.toList() returns an unmodifiable list, whereas Collectors.toList() does not guarantee a particular mutability implementation.

18. groupingBy() – Group Employees by Department


Map<String, List<Employee>> result = employees.stream()
    .collect(Collectors.groupingBy(Employee::getDepartment));

result.forEach((department, list) -> {
    System.out.println(department + " : " + list);
});
    

Group Employees by Department and Extract Employee Names


Map<String, List<String>> result = employees.stream()
    .collect(Collectors.groupingBy(
        Employee::getDepartment,
        Collectors.mapping(
            Employee::getEmpName,
            Collectors.toList()
        )
    ));
    

Group Employees by Salary


Map<Double, List<Employee>> result = employees.stream()
    .collect(Collectors.groupingBy(Employee::getSalary));
    

Count Employees in Each Department


Map<String, Long> result = employees.stream()
    .collect(Collectors.groupingBy(
        Employee::getDepartment,
        Collectors.counting()
    ));
    

Calculate Average Salary by Department


Map<String, Double> result = employees.stream()
    .collect(Collectors.groupingBy(
        Employee::getDepartment,
        Collectors.averagingDouble(Employee::getSalary)
    ));
    

Calculate Total Salary by Department


Map<String, Double> result = employees.stream()
    .collect(Collectors.groupingBy(
        Employee::getDepartment,
        Collectors.summingDouble(Employee::getSalary)
    ));
    

19. partitioningBy() – Divide Elements into Two Groups


Map<Boolean, List<Employee>> result = employees.stream()
    .collect(Collectors.partitioningBy(
        e -> e.getSalary() > 75000
    ));
    
  • true contains employees earning more than 75000.
  • false contains employees earning 75000 or less.

Count Employees in Each Partition


Map<Boolean, Long> result = employees.stream()
    .collect(Collectors.partitioningBy(
        e -> e.getSalary() > 75000,
        Collectors.counting()
    ));
    

20. Collectors.joining() – Join Strings


String result = employees.stream()
    .map(Employee::getEmpName)
    .collect(Collectors.joining(", "));

// With prefix and suffix
String names = employees.stream()
    .map(Employee::getEmpName)
    .collect(Collectors.joining(", ", "[", "]"));
    

21. Collectors.toMap() – Convert List into Map


// Employee ID as key and employee name as value
Map<Integer, String> result = employees.stream()
    .collect(Collectors.toMap(
        Employee::getEmpID,
        Employee::getEmpName
    ));

// Employee name as key and salary as value
Map<String, Double> result = employees.stream()
    .collect(Collectors.toMap(
        Employee::getEmpName,
        Employee::getSalary
    ));

// Handle duplicate keys
Map<String, Double> result = employees.stream()
    .collect(Collectors.toMap(
        Employee::getDepartment,
        Employee::getSalary,
        (oldValue, newValue) -> oldValue + newValue
    ));
    

The third argument is a merge function. It decides what to do when duplicate keys occur.

22. Collectors.summarizingDouble()


DoubleSummaryStatistics stats = employees.stream()
    .collect(Collectors.summarizingDouble(Employee::getSalary));

System.out.println(stats.getCount());
System.out.println(stats.getSum());
System.out.println(stats.getMin());
System.out.println(stats.getMax());
System.out.println(stats.getAverage());
    

23. Collectors.maxBy() and minBy()

Find the highest-paid employee in each department:


Map<String, Optional<Employee>> result = employees.stream()
    .collect(Collectors.groupingBy(
        Employee::getDepartment,
        Collectors.maxBy(
            Comparator.comparingDouble(Employee::getSalary)
        )
    ));
    

Find the lowest-paid employee in each department:


Map<String, Optional<Employee>> result = employees.stream()
    .collect(Collectors.groupingBy(
        Employee::getDepartment,
        Collectors.minBy(
            Comparator.comparingDouble(Employee::getSalary)
        )
    ));
    

Using collectingAndThen()


Map<String, Employee> result = employees.stream()
    .collect(Collectors.groupingBy(
        Employee::getDepartment,
        Collectors.collectingAndThen(
            Collectors.maxBy(
                Comparator.comparingDouble(Employee::getSalary)
            ),
            Optional::get
        )
    ));
    

This is safe here because each department group is non-empty.

24. flatMap() – Flatten Nested Collections


List<List<Integer>> numbers = Arrays.asList(
    Arrays.asList(1, 2, 3),
    Arrays.asList(4, 5, 6),
    Arrays.asList(7, 8, 9)
);

List<Integer> result = numbers.stream()
    .flatMap(List::stream)
    .collect(Collectors.toList());
    

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9]
map() flatMap()
Transforms each element.Transforms and flattens elements.
One input produces one output.One input can produce multiple outputs.
Preserves nested structure.Removes one level of nesting.

Part 2: Java Streams with Set

25. Create a Stream from Set


Set<String> names = new HashSet<>();

names.add("Sumit");
names.add("Rahul");
names.add("Amit");
names.add("Priya");

names.stream()
    .forEach(System.out::println);
    

Note: HashSet does not guarantee insertion order.

26. Filter Set Elements


Set<Integer> numbers = new HashSet<>(
    Arrays.asList(10, 20, 30, 40, 50, 60)
);

Set<Integer> result = numbers.stream()
    .filter(n -> n > 30)
    .collect(Collectors.toSet());
    

27. Sort Set Elements

Sort numbers in ascending order:


List<Integer> result = numbers.stream()
    .sorted()
    .collect(Collectors.toList());
    

Sort numbers in descending order:


List<Integer> result = numbers.stream()
    .sorted(Comparator.reverseOrder())
    .collect(Collectors.toList());
    

Sort employee Set by salary:


Set<Employee> employeeSet = new HashSet<>(employees);

List<Employee> result = employeeSet.stream()
    .sorted(Comparator.comparingDouble(Employee::getSalary))
    .collect(Collectors.toList());
    

28. Convert List to Set


Set<String> result = employees.stream()
    .map(Employee::getEmpName)
    .collect(Collectors.toSet());
    

29. Convert Set to List


List<String> result = names.stream()
    .collect(Collectors.toList());
    

30. Find Duplicate Elements in a List Using Set


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

Set<Integer> seen = new HashSet<>();

Set<Integer> duplicates = numbers.stream()
    .filter(n -> !seen.add(n))
    .collect(Collectors.toSet());

System.out.println(duplicates);
    

Output: [10, 20]

31. Find Unique Elements Using Set

Find elements that occur exactly once:


Map<Integer, Long> frequency = numbers.stream()
    .collect(Collectors.groupingBy(
        Function.identity(),
        Collectors.counting()
    ));

Set<Integer> unique = frequency.entrySet().stream()
    .filter(e -> e.getValue() == 1)
    .map(Map.Entry::getKey)
    .collect(Collectors.toSet());
    

32. Set Union, Intersection and Difference


Set<Integer> set1 = new HashSet<>(
    Arrays.asList(10, 20, 30, 40)
);

Set<Integer> set2 = new HashSet<>(
    Arrays.asList(30, 40, 50, 60)
);
    

Union – Combine All Elements


Set<Integer> union = Stream.concat(
        set1.stream(),
        set2.stream()
    )
    .collect(Collectors.toSet());
    

Output: [10, 20, 30, 40, 50, 60]

Intersection – Find Common Elements


Set<Integer> intersection = set1.stream()
    .filter(set2::contains)
    .collect(Collectors.toSet());
    

Output: [30, 40]

Difference – Elements Present in set1 but Not set2


Set<Integer> difference = set1.stream()
    .filter(n -> !set2.contains(n))
    .collect(Collectors.toSet());
    

Output: [10, 20]

Symmetric Difference


Set<Integer> symmetricDifference = Stream.concat(
        set1.stream().filter(n -> !set2.contains(n)),
        set2.stream().filter(n -> !set1.contains(n))
    )
    .collect(Collectors.toSet());
    

Output: [10, 20, 50, 60]

Part 3: Java Streams with Map

A Map stores data in key-value pairs. Unlike List and Set, a Map does not directly provide a stream() method.

  • map.entrySet().stream() – Stream of key-value entries.
  • map.keySet().stream() – Stream of keys.
  • map.values().stream() – Stream of values.

33. Create a Stream from Map


Map<Integer, String> map = new HashMap<>();

map.put(101, "Sumit");
map.put(102, "Rahul");
map.put(103, "Amit");
map.put(104, "Priya");

// Stream using entrySet
map.entrySet().stream()
    .forEach(System.out::println);

// Stream using keySet
map.keySet().stream()
    .forEach(System.out::println);

// Stream using values
map.values().stream()
    .forEach(System.out::println);
    

34. Filter Map by Key


Map<Integer, String> result = map.entrySet().stream()
    .filter(e -> e.getKey() > 102)
    .collect(Collectors.toMap(
        Map.Entry::getKey,
        Map.Entry::getValue
    ));
    

35. Filter Map by Value


Map<Integer, String> result = map.entrySet().stream()
    .filter(e -> e.getValue().startsWith("S"))
    .collect(Collectors.toMap(
        Map.Entry::getKey,
        Map.Entry::getValue
    ));
    

36. Sort Map by Key

Sort Map by key in ascending order:


Map<Integer, String> result = map.entrySet().stream()
    .sorted(Map.Entry.comparingByKey())
    .collect(Collectors.toMap(
        Map.Entry::getKey,
        Map.Entry::getValue,
        (a, b) -> a,
        LinkedHashMap::new
    ));
    

Sort Map by key in descending order:


Map<Integer, String> result = map.entrySet().stream()
    .sorted(Map.Entry.<Integer, String>comparingByKey().reversed())
    .collect(Collectors.toMap(
        Map.Entry::getKey,
        Map.Entry::getValue,
        (a, b) -> a,
        LinkedHashMap::new
    ));
    

37. Sort Map by Value

Sort Map by value in ascending order:


Map<Integer, String> result = map.entrySet().stream()
    .sorted(Map.Entry.comparingByValue())
    .collect(Collectors.toMap(
        Map.Entry::getKey,
        Map.Entry::getValue,
        (a, b) -> a,
        LinkedHashMap::new
    ));
    

Sort Map by value in descending order:


Map<Integer, String> result = map.entrySet().stream()
    .sorted(
        Map.Entry.<Integer, String>comparingByValue().reversed()
    )
    .collect(Collectors.toMap(
        Map.Entry::getKey,
        Map.Entry::getValue,
        (a, b) -> a,
        LinkedHashMap::new
    ));
    

LinkedHashMap preserves sorted insertion order. A regular HashMap does not guarantee that order.

38. Sort Map by Value Using Custom Comparator

Sort Map by employee name length:


Map<Integer, String> result = map.entrySet().stream()
    .sorted(Comparator.comparing(
        e -> e.getValue().length()
    ))
    .collect(Collectors.toMap(
        Map.Entry::getKey,
        Map.Entry::getValue,
        (a, b) -> a,
        LinkedHashMap::new
    ));
    

Sort Map values alphabetically in descending order:


Map<Integer, String> result = map.entrySet().stream()
    .sorted(Map.Entry.<Integer, String>comparingByValue().reversed())
    .collect(Collectors.toMap(
        Map.Entry::getKey,
        Map.Entry::getValue,
        (a, b) -> a,
        LinkedHashMap::new
    ));
    

39. Map Keys to List


List<Integer> keys = map.entrySet().stream()
    .map(Map.Entry::getKey)
    .collect(Collectors.toList());

// Alternative
List<Integer> keys = new ArrayList<>(map.keySet());
    

40. Map Values to List


List<String> values = map.entrySet().stream()
    .map(Map.Entry::getValue)
    .collect(Collectors.toList());

// Alternative
List<String> values = new ArrayList<>(map.values());
    

41. Convert Map to List of Map.Entry


List<Map.Entry<Integer, String>> result = map.entrySet()
    .stream()
    .collect(Collectors.toList());
    

42. Convert List to Map


Map<Integer, String> result = employees.stream()
    .collect(Collectors.toMap(
        Employee::getEmpID,
        Employee::getEmpName
    ));
    

43. Count Map Values


Map<String, Integer> marks = new HashMap<>();

marks.put("Math", 90);
marks.put("English", 80);
marks.put("Science", 95);
marks.put("History", 70);

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

44. Calculate Sum, Average, Min and Max from Map


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

double average = marks.values().stream()
    .mapToInt(Integer::intValue)
    .average()
    .orElse(0);

int min = marks.values().stream()
    .mapToInt(Integer::intValue)
    .min()
    .orElse(0);

int max = marks.values().stream()
    .mapToInt(Integer::intValue)
    .max()
    .orElse(0);
    

45. Find Map Entry with Maximum Value


Optional<Map.Entry<String, Integer>> max = marks.entrySet()
    .stream()
    .max(Map.Entry.comparingByValue());

Optional<Map.Entry<String, Integer>> min = marks.entrySet()
    .stream()
    .min(Map.Entry.comparingByValue());

// Get only the key of maximum entry
String subject = marks.entrySet().stream()
    .max(Map.Entry.comparingByValue())
    .map(Map.Entry::getKey)
    .orElse(null);
    

46. Group Map Entries by Value


Map<Integer, String> data = new HashMap<>();

data.put(101, "QA");
data.put(102, "Dev");
data.put(103, "QA");
data.put(104, "HR");
data.put(105, "Dev");

Map<String, List<Integer>> result = data.entrySet().stream()
    .collect(Collectors.groupingBy(
        Map.Entry::getValue,
        Collectors.mapping(
            Map.Entry::getKey,
            Collectors.toList()
        )
    ));
    

Output structure:


QA  = [101, 103]
Dev = [102, 105]
HR  = [104]
    

47. Convert Map to Another Map Using map()

Change all Map values to uppercase:


Map<Integer, String> result = map.entrySet().stream()
    .collect(Collectors.toMap(
        Map.Entry::getKey,
        e -> e.getValue().toUpperCase()
    ));
    

Multiply all Map values by 2:


Map<String, Integer> result = marks.entrySet().stream()
    .collect(Collectors.toMap(
        Map.Entry::getKey,
        e -> e.getValue() * 2
    ));
    

48. Find Duplicate Values in Map


Map<Integer, String> data = new HashMap<>();

data.put(1, "QA");
data.put(2, "Dev");
data.put(3, "QA");
data.put(4, "HR");
data.put(5, "Dev");

Set<String> duplicates = data.values().stream()
    .collect(Collectors.groupingBy(
        Function.identity(),
        Collectors.counting()
    ))
    .entrySet().stream()
    .filter(e -> e.getValue() > 1)
    .map(Map.Entry::getKey)
    .collect(Collectors.toSet());
    

Output: [QA, Dev]

Part 4: Advanced Java Stream Examples

These examples are particularly useful for Java interviews and automation framework development.

49. Group Employees by Department and Sort by Salary

Sort employees within each department by salary ascending:


Map<String, List<Employee>> result = employees.stream()
    .collect(Collectors.groupingBy(
        Employee::getDepartment,
        Collectors.collectingAndThen(
            Collectors.toList(),
            list -> list.stream()
                .sorted(Comparator.comparingDouble(Employee::getSalary))
                .collect(Collectors.toList())
        )
    ));
    

For descending salary:


Map<String, List<Employee>> result = employees.stream()
    .collect(Collectors.groupingBy(
        Employee::getDepartment,
        Collectors.collectingAndThen(
            Collectors.toList(),
            list -> list.stream()
                .sorted(
                    Comparator.comparingDouble(Employee::getSalary).reversed()
                )
                .collect(Collectors.toList())
        )
    ));
    

50. Group Employees by Department and Employee Name


Map<String, List<String>> result = employees.stream()
    .sorted(Comparator.comparing(Employee::getEmpName))
    .collect(Collectors.groupingBy(
        Employee::getDepartment,
        Collectors.mapping(
            Employee::getEmpName,
            Collectors.toList()
        )
    ));
    

51. Find the Second-Highest Salary


Optional<Double> result = employees.stream()
    .map(Employee::getSalary)
    .distinct()
    .sorted(Comparator.reverseOrder())
    .skip(1)
    .findFirst();
    

52. Find the Top Three Highest Salaries


List<Double> result = employees.stream()
    .map(Employee::getSalary)
    .distinct()
    .sorted(Comparator.reverseOrder())
    .limit(3)
    .collect(Collectors.toList());
    

53. Find the Highest-Paid Employee in Each Department


Map<String, Employee> result = employees.stream()
    .collect(Collectors.toMap(
        Employee::getDepartment,
        Function.identity(),
        BinaryOperator.maxBy(
            Comparator.comparingDouble(Employee::getSalary)
        )
    ));
    

54. Find the Employee with the Second-Highest Salary in Each Department


Map<String, Optional<Employee>> result = employees.stream()
    .collect(Collectors.groupingBy(
        Employee::getDepartment,
        Collectors.collectingAndThen(
            Collectors.toList(),
            list -> list.stream()
                .sorted(
                    Comparator.comparingDouble(Employee::getSalary).reversed()
                )
                .map(Employee::getSalary)
                .distinct()
                .skip(1)
                .findFirst()
                .flatMap(salary -> list.stream()
                    .filter(e -> e.getSalary() == salary)
                    .findFirst())
        )
    ));
    

55. Group Employees by Department and Find Total Salary


Map<String, Double> result = employees.stream()
    .collect(Collectors.groupingBy(
        Employee::getDepartment,
        Collectors.summingDouble(Employee::getSalary)
    ));
    

56. Find Employee Names with Salary Greater Than Average Salary


double averageSalary = employees.stream()
    .mapToDouble(Employee::getSalary)
    .average()
    .orElse(0);

List<String> result = employees.stream()
    .filter(e -> e.getSalary() > averageSalary)
    .map(Employee::getEmpName)
    .collect(Collectors.toList());
    

57. Sort by Multiple Fields

Sort by department ascending and salary descending:


List<Employee> result = employees.stream()
    .sorted(
        Comparator.comparing(Employee::getDepartment)
            .thenComparing(
                Comparator.comparingDouble(Employee::getSalary).reversed()
            )
    )
    .collect(Collectors.toList());
    

Sort by salary descending and then employee name ascending:


List<Employee> result = employees.stream()
    .sorted(
        Comparator.comparingDouble(Employee::getSalary).reversed()
            .thenComparing(Employee::getEmpName)
    )
    .collect(Collectors.toList());
    

58. Convert List of Lists into a Single List


List<List<String>> data = Arrays.asList(
    Arrays.asList("A", "B"),
    Arrays.asList("C", "D"),
    Arrays.asList("E", "F")
);

List<String> result = data.stream()
    .flatMap(Collection::stream)
    .collect(Collectors.toList());
    

59. Generate a Frequency Map of Elements


List<String> names = Arrays.asList(
    "Sumit", "Rahul", "Sumit", "Amit", "Rahul", "Sumit"
);

Map<String, Long> result = names.stream()
    .collect(Collectors.groupingBy(
        Function.identity(),
        Collectors.counting()
    ));
    

60. Find the First Non-Repeated Character


String input = "swiss";

Map<Character, Long> frequency = input.chars()
    .mapToObj(c -> (char) c)
    .collect(Collectors.groupingBy(
        Function.identity(),
        LinkedHashMap::new,
        Collectors.counting()
    ));

Character result = frequency.entrySet().stream()
    .filter(e -> e.getValue() == 1)
    .map(Map.Entry::getKey)
    .findFirst()
    .orElse(null);

System.out.println(result);
    

Output: w

LinkedHashMap is used to preserve character insertion order.

Part 5: Parallel Streams

Parallel streams allow collection processing to be divided across multiple threads.

Normal Stream


employees.stream()
    .filter(e -> e.getSalary() > 75000)
    .forEach(System.out::println);
    

Parallel Stream


employees.parallelStream()
    .filter(e -> e.getSalary() > 75000)
    .forEach(System.out::println);
    

Convert Stream into Parallel Stream


employees.stream()
    .parallel()
    .filter(e -> e.getSalary() > 75000)
    .forEach(System.out::println);
    

Sequential vs Parallel Stream

Stream Parallel Stream
Executes sequentially.Executes using multiple threads.
Usually simpler.Requires more care.
Predictable encounter order with ordered operations.Execution order may differ.
Suitable for small and ordinary tasks.Can help with large, CPU-intensive tasks.
Less concurrency overhead.Additional concurrency overhead.

Important: Parallel streams are not always faster. Avoid shared mutable collections and stateful side effects when using parallel processing.

Part 6: Important Java Stream Methods Cheat Sheet

61. Intermediate Operations

Method Description Example
filter()Filter elements.filter(n -> n > 10)
map()Transform elements.map(String::toUpperCase)
flatMap()Flatten nested collections.flatMap(List::stream)
sorted()Sort elements.sorted()
distinct()Remove duplicates.distinct()
limit()Get first N elements.limit(5)
skip()Skip first N elements.skip(2)
peek()Inspect elements during processing.peek(System.out::println)
mapToInt()Convert to IntStream.mapToInt(Integer::intValue)
mapToDouble()Convert to DoubleStream.mapToDouble(Employee::getSalary)
sequential()Make stream sequential.sequential()
parallel()Make stream parallel.parallel()

62. Terminal Operations

MethodDescription
collect()Collect elements into a collection.
toList()Collect into an unmodifiable List.
forEach()Iterate over elements.
count()Count elements.
min()Find minimum.
max()Find maximum.
reduce()Combine elements into one result.
findFirst()Find first element.
findAny()Find any element.
anyMatch()Check whether any element matches.
allMatch()Check whether all elements match.
noneMatch()Check whether no elements match.
toArray()Convert to array.

63. Important Collectors Methods

MethodDescription
toList()Collect into List.
toSet()Collect into Set.
toMap()Collect into Map.
groupingBy()Group elements.
partitioningBy()Divide into true/false groups.
counting()Count elements.
joining()Join strings.
mapping()Transform elements while collecting.
filtering()Filter while collecting.
summingInt()Calculate integer sum.
summingDouble()Calculate double sum.
averagingInt()Calculate integer average.
averagingDouble()Calculate double average.
maxBy()Find maximum.
minBy()Find minimum.
collectingAndThen()Apply another operation after collecting.
summarizingInt()Get integer statistics.
summarizingDouble()Get double statistics.
reducing()Reduce elements.

Part 7: List vs Set vs Map Stream Syntax

Collection Stream Creation Example
List list.stream() list.stream().filter(...)
Set set.stream() set.stream().sorted()
Map keys map.keySet().stream() map.keySet().stream()
Map values map.values().stream() map.values().stream()
Map entries map.entrySet().stream() map.entrySet().stream()

Part 8: Important Interview Questions

  1. Find the second-highest number from a List.
  2. Find duplicate elements from a List.
  3. Find unique elements from a List.
  4. Find the first non-repeated character in a String.
  5. Find the frequency of each character in a String.
  6. Sort employees by salary ascending and descending.
  7. Find the highest-paid employee.
  8. Find the second-highest-paid employee.
  9. Group employees by department.
  10. Count employees in each department.
  11. Calculate average salary by department.
  12. Find the highest-paid employee in each department.
  13. Find the lowest-paid employee in each department.
  14. Sort Map by key.
  15. Sort Map by value.
  16. Find duplicate values in a Map.
  17. Convert List into Map.
  18. Convert Map into List.
  19. Find common elements between two Sets.
  20. Flatten a nested List using flatMap().

64. Java Stream Practice Exercises

  1. Find employees whose salary is greater than 80000.
    
    filter(e -> e.getSalary() > 80000)
            
  2. Sort employees by ID in descending order.
    
    sorted(Comparator.comparingInt(Employee::getEmpID).reversed())
            
  3. Group employees by department.
    
    collect(Collectors.groupingBy(Employee::getDepartment))
            
  4. Find the average employee salary.
    
    mapToDouble(Employee::getSalary).average()
            
  5. Find the highest salary.
    
    mapToDouble(Employee::getSalary).max()
            
  6. Count employees in each department.
    
    collect(Collectors.groupingBy(
        Employee::getDepartment,
        Collectors.counting()
    ))
            
  7. Find duplicate numbers using a Set.
    
    filter(n -> !seen.add(n))
            
  8. Sort a Map by value descending.
    
    sorted(Map.Entry.<K,V>comparingByValue().reversed())
            

65. Important Tips and Best Practices

  1. Prefer method references such as Employee::getSalary when they improve readability.
  2. Use Optional when working with findFirst(), min() and max().
  3. Use mapToInt() and mapToDouble() for numerical calculations.
  4. Use groupingBy() for grouping and partitioningBy() for two-way classification.
  5. Use LinkedHashMap when the order of sorted Map entries must be preserved.
  6. Do not reuse a Stream after a terminal operation. Create a new Stream instead.
  7. Avoid modifying the original collection while streaming over it.
  8. Use parallelStream() only after considering performance and thread safety.
  9. Remember that distinct() on custom objects requires proper equals() and hashCode() implementations.
  10. Use Collectors.toMap() with a merge function when duplicate keys are possible.

Conclusion

Java Stream API is an important feature for processing collections efficiently and writing clean, readable Java code. Practice List, Set, and Map operations along with Comparator, groupingBy(), mapping(), flatMap(), and Collectors to improve your Java programming and interview skills.

Recommended learning order: filter() → map() → sorted() → collect() → reduce() → groupingBy() → toMap() → flatMap() → Comparator → advanced employee-based examples.

No comments:

Post a Comment