You can use the Java Stream API to filter and return employee names that start with "SU" (case-insensitive) by following these steps:
- Convert the list of employee names to a stream using the
stream()method. - Use the
filter()method to filter names that start with"SU"(ignoring case). - Use
toLowerCase()ortoUpperCase()to make the comparison case-insensitive. - Collect the filtered names into a list using
collect()andCollectors.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 "SU" (case-insensitive)
List<String> filteredEmployees = employees.stream()
.filter(name -> name.toUpperCase().startsWith("SU"))
.collect(Collectors.toList());
// Print the filtered names
System.out.println(filteredEmployees);
}
}
Explanation:
stream(): Converts the list to a stream.filter(): Filters the stream based on whether the name starts with"SU"(case-insensitive). ThetoUpperCase()method is used to normalize the case for comparison.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.