gpt-4-0314· openai
Suzhen/CodeChat
Java Stream API program to find 2 unique lastnames of employee whose city is Mumbai in…
- User
Java Stream API program to find 2 unique lastnames of employee whose city is Mumbai in address of employee
- Assistant
To find the 2 unique last names of employees whose city is Mumbai, you can use the Java Stream API along with the filter and map methods. Here's a sample implementation using a list of Employee objects:
import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; class Address { String city; Address(String city) { this.city = city; } String getCity() { return city; } } class Employee { String firstName; String lastName; Address address; Employee(String firstName, String lastName, Address address) { this.firstName = firstName; this.lastName = lastName; this.address = address; } String getLastName() { return lastName; } Address getAddress() { return address; } } public class Main { public static void main(String[] args) { List<Employee> employees = new ArrayList<>(); employees.add(new Employee("John", "Doe", new Address("Mumbai"))); employees.add(new Employee("Jane", "Doe", new Address("Mumbai"))); employees.add(new Employee("Tom", "Smith", new Address("Mumbai"))); employees.add(new Employee("Jerry", "Brown", new Address("New York"))); employees.add(new Employee("Emma", "Watson", new Address("London"))); List<String> uniqueLastNamesInMumbai = employees.stream() .filter(employee -> "Mumbai".equalsIgnoreCase(employee.getAddress().getCity())) .map(Employee::getLastName) .distinct() .limit(2) .collect(Collectors.toList()); System.out.println("2 unique last names in Mumbai: " + uniqueLastNamesInMumbai); } }