Given a list of employee names, how would you use the Java Stream API to filter and return names that start with "SU" (case-insensitive)?

You can use the Java Stream API to filter and return employee names that start with "SU" (case-insensitive) by following these steps:

  1. Convert the list of employee names to a stream using the stream() method.
  2. Use the filter() method to filter names that start with "SU" (ignoring case).
  3. Use toLowerCase() or toUpperCase() to make the comparison case-insensitive.
  4. Collect the filtered names into a list using collect() and Collectors.toList().

Example Code:

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class EmployeeFilter {  

public static void main(String args) {

// List of employee names

List<String> employees = Arrays.asList("Susan", "susan", "SUzanne", "John", "Su", "Sunny", "Michael");

// Filter names that start with &quot;SU&quot; (case-insensitive)
List&lt;String&gt; filteredEmployees = employees.stream()
    .filter(name -&gt; name.toUpperCase().startsWith(&quot;SU&quot;))
    .collect(Collectors.toList());

// Print the filtered names
System.out.println(filteredEmployees);

}


}  

Explanation:

  1. stream(): Converts the list to a stream.
  2. filter(): Filters the stream based on whether the name starts with "SU" (case-insensitive). The toUpperCase() method is used to normalize the case for comparison.
  3. collect(Collectors.toList()): Collects the filtered names into a list.

Output:

[Susan, susan, SUzanne, Su, Sunny]

In this example, all names that start with "SU" or "su" (case-insensitive) are returned. The toUpperCase() ensures that the comparison is case-insensitive.