Monday, 26 May 2025

Java 8 Interview question with solution

 Example:1 / Filter employees with salary > 50000 and get their names(map example)

Solution:

Output:

High Earning Employees: [Alice, Charlie]   

Program:

import java.util.*;

import java.util.stream.Collectors;

class Employee {

    String name;

    double salary;

    Employee(String name, double salary) {

        this.name = name;

        this.salary = salary;

    }

}

public class EmployeeMapExample {

    public static void main(String[] args) {

        List<Employee> employees = Arrays.asList(

                new Employee("Alice", 60000),

                new Employee("Bob", 45000),

                new Employee("Charlie", 70000)

        );


        // Filter employees with salary > 50000 and get their names

        List<String> highEarnerNames = employees.stream()

                .filter(emp -> emp.salary > 50000) // condition

                .map(emp -> emp.name)             // transform Employee to name

                .collect(Collectors.toList());    // collect as List<String>


        System.out.println("High Earning Employees: " + highEarnerNames);

    }

}