Employee Class Based Java 8 Interview Questions

Are you preparing for a Java 8 interview and not getting much questions for practice? So you are at right place. In this article we have taken a Employee class with some fields like name, salary, department, age, gender etc and will created all possible real time scenario. This is the exact scenario that will be asked in interview when you will apprear for a Java Developer role.

These all are a interview ready questions, you just have to prepare and appear for an interview. You don’t have to put extra effort on finding questions, that part we have already done.

In this blog along with real time scenario based java 8 questions, we have also providing you with detailed answers to help you ace your interview. This explanation will help to understand and explain the logic to interviewer if they ask. This is best collection I can say on interview and applicable for a fresher or an experienced java developer. Topics of Java 8 that you are going to use in this journey are lambda expressions, functional interfaces, stream API and various intermediate and terminal functions. So, let’s dive in and make sure you’re well-prepared for your next Java 8 interview!

Employee.java

import java.time.LocalDate;

class Employee {
    private String name;
    private double salary;
    private String department;
    private int age;
    private String gender;
    private LocalDate dateOfJoining;

    public Employee() {

    }

    public Employee(String name, double salary, String department, int age, String gender, LocalDate dateOfJoining) {
        this.name = name;
        this.salary = salary;
        this.department = department;
        this.age = age;
        this.gender = gender;
        this.dateOfJoining = dateOfJoining;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }

    public String getDepartment() {
        return department;
    }

    public void setDepartment(String department) {
        this.department = department;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public LocalDate getDateOfJoining() { return dateOfJoining; }

    public void setDateOfJoining(LocalDate dateOfJoining) { this.dateOfJoining = dateOfJoining; }

    @Override
    public String toString() {
        return "Employee{" +
                "name='" + name + '\'' +
                ", salary=" + salary +
                ", department='" + department + '\'' +
                ", age=" + age +
                ", gender='" + gender + '\'' +
                ", dateOfJoining=" + dateOfJoining +
                '}';
    }
}

Note:

Please add the below import statement in your main class to work with collection and stream.

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

EmployeeDataGenerator.java

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

public class EmployeeDataGenerator {
    public static List<Employee> generateSampleData() {
        List<Employee> employeeList = new ArrayList<>();

        employeeList.add(new Employee("John Doe", 60000.0, "IT", 30, "Male", LocalDate.of(2019, 5, 15)));
        employeeList.add(new Employee("Jane Smith", 70000.0, "HR", 28, "Female", LocalDate.of(2020, 8, 22)));
        employeeList.add(new Employee("Robert Johnson", 80000.0, "Finance", 35, "Male", LocalDate.of(2018, 3, 10)));
        employeeList.add(new Employee("Emily Davis", 55000.0, "Marketing", 25, "Female", LocalDate.of(2021, 1, 5)));
        employeeList.add(new Employee("Michael Brown", 75000.0, "Engineering", 32, "Male", LocalDate.of(2017, 11, 18)));
        employeeList.add(new Employee("Alice Miller", 72000.0, "Sales", 29, "Female", LocalDate.of(2019, 9, 8)));
        employeeList.add(new Employee("David Wilson", 68000.0, "IT", 31, "Male", LocalDate.of(2020, 4, 30)));
        employeeList.add(new Employee("Sophia Davis", 85000.0, "Finance", 28, "Female", LocalDate.of(2018, 7, 12)));
        employeeList.add(new Employee("Henry Johnson", 60000.0, "Engineering", 27, "Male", LocalDate.of(2022, 2, 15)));
        employeeList.add(new Employee("Olivia Brown", 67000.0, "Marketing", 26, "Female", LocalDate.of(2021, 6, 25)));
        employeeList.add(new Employee("Ethan Smith", 78000.0, "Sales", 33, "Male", LocalDate.of(2017, 12, 5)));
        employeeList.add(new Employee("Ava Wilson", 59000.0, "HR", 24, "Female", LocalDate.of(2019, 10, 20)));
        employeeList.add(new Employee("Liam Davis", 71000.0, "Engineering", 30, "Male", LocalDate.of(2018, 1, 8)));
        employeeList.add(new Employee("Mia Johnson", 73000.0, "IT", 34, "Female", LocalDate.of(2020, 3, 22)));
        employeeList.add(new Employee("Noah Miller", 69000.0, "Finance", 32, "Male", LocalDate.of(2017, 8, 14)));

        return employeeList;
    }
}

Scenario Based Java 8 Interview Questions

1. Filtering Employees

Given a list of `Employee` objects, filter and retrieve all male employees in the “Engineering” department using Java 8 Streams.

import java.util.*;
import java.util.stream.*;
class FilteringEmployees{
    public static void main(String ...a){
        List<Employee> employeeList = EmployeeDataGenerator.generateSampleData();
                                        
        List<Employee> employeeListOutput = employeeList.stream()
                                    .filter(s->(s.getGender().equalsIgnoreCase("male") && s.getDepartment().equalsIgnoreCase("Engineering")))
                                    .collect(Collectors.toList());
        
        employeeListOutput.forEach(e->System.out.println(e.getName()));    
    }
}

Output

Michael Brown
Henry Johnson
Liam Davis

2. Mapping Names to Uppercase

Transform the names of all employees to uppercase using the map operation in streams.

class ToUpperCase{
    public static void main(String ...args){
        List<Employee> employeeList = EmployeeDataGenerator.generateSampleData();

        List<String > employeeListOutput = employeeList.stream()
                .map(e->e.getName().toUpperCase())
                .collect(Collectors.toList());

        employeeListOutput.forEach(System.out::println);
    }
}

Example

JOHN DOE
JANE SMITH
ROBERT JOHNSON
EMILY DAVIS
MICHAEL BROWN
ALICE MILLER
DAVID WILSON
SOPHIA DAVIS
HENRY JOHNSON
OLIVIA BROWN
ETHAN SMITH
AVA WILSON
LIAM DAVIS
MIA JOHNSON
NOAH MILLER

3. Sorting Employees Ascending Order

Sort a list of ‘Employee’ objects by their salaries in Ascending order using Java 8 Streams.

class SortEmployeeAscending{
    public static void main(String ...args){
        List<Employee> employeeList = EmployeeDataGenerator.generateSampleData();

        List<Employee> employeeListOutput = employeeList.stream()
                .sorted(Comparator.comparing(Employee::getSalary))
                .collect(Collectors.toList());

        employeeListOutput.forEach(e->System.out.println(e.getName()+" "+e.getSalary()));
    }
}

Output

John Doe 60000.0
Henry Johnson 60000.0
Olivia Brown 67000.0
David Wilson 68000.0
Noah Miller 69000.0
Jane Smith 70000.0
Liam Davis 71000.0
Alice Miller 72000.0
Mia Johnson 73000.0
Michael Brown 75000.0
Ethan Smith 78000.0
Robert Johnson 80000.0
Sophia Davis 85000.0

4. Sorting Employees Descending Order

Sort a list of `Employee` objects by their salaries in descending order using Java 8 Streams.

import java.util.*;
import java.util.stream.*;
class SortEmployeeDescending{
    public static void main(String ...a){
        List<Employee> employeeList = EmployeeDataGenerator.generateSampleData();
                                        
        List<Employee> employeeListOutput = employeeList.stream()
                                    .sorted(Comparator.comparing(Employee::getSalary).reversed())
                                    .collect(Collectors.toList());
        
        employeeListOutput.forEach(e->System.out.println(e.getName()+" "+e.getSalary()));    
    }
}

Output

Sophia Davis 85000.0
Robert Johnson 80000.0
Ethan Smith 78000.0
Michael Brown 75000.0
Mia Johnson 73000.0
Alice Miller 72000.0
Liam Davis 71000.0
Jane Smith 70000.0
Noah Miller 69000.0
David Wilson 68000.0
Olivia Brown 67000.0
John Doe 60000.0
Henry Johnson 60000.0
Ava Wilson 59000.0
Emily Davis 55000.0

5. Group Employees by Gender

Group the employees by their gender and print the result using the groupingBy collector.

class GroupByGender{
    public static void main(String ...args){
        List<Employee> employeeList = EmployeeDataGenerator.generateSampleData();

        Map<String,List<Employee>> employeeListOutput = employeeList.stream()
                .collect(Collectors.groupingBy(s->s.getGender()));

        employeeListOutput.forEach((k,v)->{
            System.out.println("Gender : "+k);
            v.forEach(System.out::println);
            System.out.println("-----------------------------");
        });
    }
}

6. Group Employees By Department

Group a list of `Employee` objects by their departments using Java 8 Streams, resulting in a map where keys represent departments and values are lists of employees in that department.

import java.util.*;
import java.util.stream.*;
class GroupByDepartment{
    public static void main(String ...a){
        List<Employee> employeeList = EmployeeDataGenerator.generateSampleData();
        
        Map<String,List<Employee>> empDepList = employeeList.stream()
                                .collect(Collectors.groupingBy(Employee::getDepartment));
                                
        empDepList.forEach((department,employee)->{
            System.out.println("Department =" +department);
            employee.forEach(System.out::println); 
            System.out.println("---------------------------");
        });
    }
}

Output

Department =Engineering
Employee{name='Pawan', salary=10332.0, department='Engineering', age=35, gender='Male'}
Employee{name='Deepika', salary=9332.0, department='Engineering', age=19, gender='Female'}
Employee{name='Saloni', salary=8332.0, department='Engineering', age=21, gender='Female'}
Employee{name='Rittick', salary=23211.0, department='Engineering', age=37, gender='Male'}
---------------------------
Department =Sales
Employee{name='Naresh', salary=1233.0, department='Sales', age=34, gender='Male'}
Employee{name='Siddhi', salary=31332.0, department='Sales', age=32, gender='Female'}
Employee{name='Sayan', salary=43211.0, department='Sales', age=37, gender='Male'}
---------------------------
Department =Admin
Employee{name='Prakash', salary=12332.0, department='Admin', age=34, gender='Male'}
Employee{name='Sonu', salary=23321.0, department='Admin', age=41, gender='Female'}
Employee{name='Anjali', salary=21332.0, department='Admin', age=23, gender='Female'}
---------------------------

7. Counting Employees by Gender

Count the number of employees for each gender using the groupingBy and counting collectors.

class CountByGender{
    public static void main(String ...args){
        List<Employee> employeeList = EmployeeDataGenerator.generateSampleData();

        Map<String,Long> employeeListOutput = employeeList.stream()
                .collect(Collectors.groupingBy(s->s.getGender(),Collectors.counting()));

        employeeListOutput.forEach((k,v)->{
            System.out.println("Gender : "+k + " and Count : "+v);
        });
    }
}

8. Salary Summation

Calculate the total salary of all female employees in a list of `Employee` objects using Java 8 Streams.

import java.util.*;
import java.util.stream.*;
class SalarySummation{
    public static void main(String ...args){
        List<Employee> employeeList = EmployeeDataGenerator.generateSampleData();
        
        Double totalSalary = employeeList.stream()
                                .filter(e->e.getGender().equals("Female"))
                                .map(e->e.getSalary())
                                .reduce(0.0,(a,b)->a+b);
                                
        System.out.println(totalSalary); 
    }
}

Output

93649.0

9. Finding Highest Salary

Find the female employee with the highest salary in a list of `Employee` objects using Java 8 Streams.

import java.util.*;
import java.util.stream.*;
class FindHighestSalary{
    public static void main(String ...args){
        List<Employee> employeeList = EmployeeDataGenerator.generateSampleData();
        
        Employee employee = employeeList.stream().filter(e->e.getGender().equals("Female"))
                                .sorted(Comparator.comparing(Employee::getSalary).reversed())
                                .findFirst().get();
                                
        System.out.println(employee); 
    }
}

Output

Employee{name='Siddhi', salary=31332.0, department='Sales', age=32, gender='Female'}

10. Extracting Names

Create a list of names (Strings) from a list of `Employee` objects using Java 8 Streams.

import java.util.*;
import java.util.stream.*;
class ExtractingNames{
    public static void main(String ...args){
        List<Employee> employeeList = EmployeeDataGenerator.generateSampleData();
        
        List<String> employeeName = employeeList.stream()
                        .map(e->e.getName())
                        .collect(Collectors.toList());
                                
        employeeName.forEach(System.out::println); 
    }
}

Output

Prakash
Pawan
Sonu
Deepika
Naresh
Saloni
Siddhi
Anjali
Sayan
Rittick

11. Conditional Mapping

Create a list of employees’ names who have a salary greater than 20,000 and are in the “Sales” department using Java 8 Streams.

import java.util.*;
import java.util.stream.*;
class ConditionalMapping{
    public static void main(String ...a){
        List<Employee> employeeList = EmployeeDataGenerator.generateSampleData();
                                        
        List<String> namesInSalesWithHighSalary = employeeList.stream()
                .filter(employee -> employee.getSalary() > 20000)
                .filter(employee -> "Sales".equals(employee.getDepartment()))
                .map(Employee::getName)
                .collect(Collectors.toList());

        System.out.println("Employees in Sales with Salary > 20,000: " + namesInSalesWithHighSalary);
    }
}

Output

Employees in Sales with Salary > 20,000: [Siddhi, Sayan]

12. Calculating Average Salary

Calculate the average salary for all employees and print it.

class AverageSalaryEmployee{
    public static void main(String ...args){
        List<Employee> employeeList = EmployeeDataGenerator.generateSampleData();

        Double employeeListOutput = employeeList.stream()
                .mapToDouble(e->e.getSalary()).average().getAsDouble();

        System.out.println("Average Salary of Employee : "+ employeeListOutput);
    }
}

13. Department Averaging

Calculate the average salary for employees in each department using Java 8 Streams.

import java.util.*;
import java.util.stream.*;
class DepartmentWiseAverageSalary{
    public static void main(String ...args){
        List<Employee> employeeList = EmployeeDataGenerator.generateSampleData();
        
        Map<String,Double> employeeName = employeeList.stream()
                            .collect(Collectors.groupingBy(Employee::getDepartment, Collectors.averagingDouble(Employee::getSalary)));
        
        System.out.println("Department wise average salary:");                        
        employeeName.forEach((k,v)->System.out.println(k+" "+v));
        
    }
}

Output

Department wise average salary:
Engineering 12801.75
Sales 25258.666666666668
Admin 18995.0

14. Salary Adjustment

Increase the salary of all female employees in the “Engineering” department by 10% using Java 8 Streams.

import java.util.*;
import java.util.stream.*;
class SalaryIncreament{
    public static void main(String ...a){
        List<Employee> employeeList = EmployeeDataGenerator.generateSampleData();
                                        
        List<Double> employeeListOutput = employeeList.stream()
                                    .filter(s->(s.getGender().equalsIgnoreCase("Female") && s.getDepartment().equalsIgnoreCase("Engineering")))
                                    .map(s->s.getSalary()+(s.getSalary()*10)/100)
                                    .collect(Collectors.toList());
        
        employeeListOutput.forEach(e->System.out.println(e));    
    }
}

Output

10265.2
9165.2

15. Senior Employees

Filter and retrieve all employees who are older than 30 years and have a salary greater than 30,000 using Java 8 Streams.

import java.util.*;
import java.util.stream.*;
class SeniorEmployee{
    public static void main(String ...a){
        List<Employee> employeeList = EmployeeDataGenerator.generateSampleData();
                                        
        List<Employee> employeeListOutput = employeeList.stream()
                                    .filter(s->(s.getAge()>30 && s.getSalary()>30000))
                                    .collect(Collectors.toList());
        
        employeeListOutput.forEach(e->System.out.println(e));    
    }
}

Output

Employee{name='Siddhi', salary=31332.0, department='Sales', age=32, gender='Female'}
Employee{name='Sayan', salary=43211.0, department='Sales', age=37, gender='Male'}

16. Departmental Leaders

Find the employee with the highest salary in each department using Java 8 Streams.

import java.util.*;
import java.util.stream.*;
class DepartmentalLeaders{
    public static void main(String ...a){
        List<Employee> employeeList = EmployeeDataGenerator.generateSampleData();
                                        
        Map<String, Employee> highestSalaryInEachDepartment = employeeList.stream()
                .collect(Collectors.toMap(
                        Employee::getDepartment,
                        e -> e,
                        (e1, e2) -> e1.getSalary() >= e2.getSalary() ? e1 : e2
                ));

        highestSalaryInEachDepartment.forEach((department, employee) ->
                System.out.println("Department: " + department + ", Highest Salary Employee: " + employee.getName()));
   
    }
}

Output

Department: Engineering, Highest Salary Employee: Rittick
Department: Sales, Highest Salary Employee: Sayan
Department: Admin, Highest Salary Employee: Sonu

17. Department Statistics

Calculate the total salary, average salary, and number of female employees in each department using Java 8 Streams.

import java.util.*;
import java.util.stream.*;
class DepartmentStatistic{
    public static void main(String ...a){
        List<Employee> employeeList = EmployeeDataGenerator.generateSampleData();
                                        
        Map<String, DoubleSummaryStatistics> departmentStatistics = employeeList.stream()
                .collect(Collectors.groupingBy(Employee::getDepartment,
                        Collectors.summarizingDouble(Employee::getSalary)));

        Map<String, Long> femaleCountByDepartment = employeeList.stream()
                .filter(employee -> "Female".equals(employee.getGender()))
                .collect(Collectors.groupingBy(Employee::getDepartment, Collectors.counting()));

        departmentStatistics.forEach((department, stats) -> {
            System.out.println("Department: " + department);
            System.out.println("Total Salary: " + stats.getSum());
            System.out.println("Average Salary: " + stats.getAverage());
            System.out.println("Number of Female Employees: " + femaleCountByDepartment.getOrDefault(department, 0L));
            System.out.println("------------------------------");
        });
   
    }
}

Output

Department: Engineering
Total Salary: 51207.0
Average Salary: 12801.75
Number of Female Employees: 2
------------------------------
Department: Sales
Total Salary: 75776.0
Average Salary: 25258.666666666668
Number of Female Employees: 1
------------------------------
Department: Admin
Total Salary: 56985.0
Average Salary: 18995.0
Number of Female Employees: 2
------------------------------

18. Employee by Salary Range

Group employees into different salary ranges (e.g., 0-10k, 10k-20k, 20k-30k, 30k-50k) using Java 8 Streams.

import java.util.*;
import java.util.stream.*;
class EmployeeSalaryRange{
    public static void main(String ...a){
        List<Employee> employeeList = EmployeeDataGenerator.generateSampleData();
                                        
         Map<String, List<Employee>> salaryRangeGroups = employeeList.stream()
                .collect(Collectors.groupingBy(employee -> getSalaryRange(employee.getSalary())));

        // Print the results
        salaryRangeGroups.forEach((range, employeeList1) -> {
            System.out.println("Salary Range: " + range);
            employeeList1.forEach(employee -> System.out.println("   " + employee));
            System.out.println("------------------------------");
        });
    }
    
    private static String getSalaryRange(double salary) {
        if (salary < 10000) {
            return "0-10k";
        } else if (salary < 20000) {
            return "10k-20k";
        } else if (salary < 30000) {
            return "20k-30k";
        } else if (salary < 50000) {
            return "30k-50k";
        } else {
            return "50k+";
        }
    }
}

Output

Salary Range: 0-10k
   Employee{name='Deepika', salary=9332.0, department='Engineering', age=19, gender='Female'}
   Employee{name='Naresh', salary=1233.0, department='Sales', age=34, gender='Male'}
   Employee{name='Saloni', salary=8332.0, department='Engineering', age=21, gender='Female'}
------------------------------
Salary Range: 20k-30k
   Employee{name='Sonu', salary=23321.0, department='Admin', age=41, gender='Female'}
   Employee{name='Anjali', salary=21332.0, department='Admin', age=23, gender='Female'}
   Employee{name='Rittick', salary=23211.0, department='Engineering', age=37, gender='Male'}
------------------------------
Salary Range: 30k-50k
   Employee{name='Siddhi', salary=31332.0, department='Sales', age=32, gender='Female'}
   Employee{name='Sayan', salary=43211.0, department='Sales', age=37, gender='Male'}
------------------------------
Salary Range: 10k-20k
   Employee{name='Prakash', salary=12332.0, department='Admin', age=34, gender='Male'}
   Employee{name='Pawan', salary=10332.0, department='Engineering', age=35, gender='Male'}
------------------------------

19. Name Concatenation

Concatenate the names of all employees in the list into a single comma-separated string using Java 8 Streams.

import java.util.*;
import java.util.stream.*;
class NameConcatenation{
    public static void main(String ...a){
        List<Employee> employeeList = EmployeeDataGenerator.generateSampleData();
                                        
         String concatenatedNames = employeeList.stream()
                .map(Employee::getName)
                .collect(Collectors.joining(", "));

        System.out.println("Concatenated Names: " + concatenatedNames);
    }
}

Output

Concatenated Names: Prakash, Pawan, Sonu, Deepika, Naresh, Saloni, Siddhi, Anjali, Sayan, Rittick

20. Printing Employment Duration

Determine and print the number of years each employee has been with the company using the ChronoUnit class.

21. Filtering Employees by Date of Joining

Filter and print the employees who joined the company after a specific date.

These scenario-based questions cover a range of tasks related to processing a list of `Employee` objects using Java 8 Streams and functional programming techniques. They will help you practice and improve your skills in working with Streams and collections of objects in Java.

How useful was this post?

Click on a star to rate it!

Average rating 5 / 5. Vote count: 2

No votes so far! Be the first to rate this post.