Scenario Based Java 8 Coding Interview Questions (For Experienced)

Generally, most websites cover basic Java 8 coding problems, But when you appear in the interview as an experience, Interviewer asks scenario-based coding questions. This question might not be simple if you have not practiced it well.

So to solve this, I have collected and prepared multiple Java 8 scenario-based tough questions. That is not simple. To solve this problem you have to think in-depth and apply different Java 8 concepts in it.

Also all listed below problem is important for all types of MNCs exams. So Please go through it one by one and solve it. First, try to solve it on your own before referring to the solution.

Scenario 1:

Employee Management System

We have a list of employees with (name, age, salary). Your task is to write a program to find the average salary of employees older than 30 using Java 8.

import java.util.*;

class Employee{
    private String name;
    private int age;
    private double salary;
    
    Employee(String name,int age,double salary){
        this.name = name;
        this.age = age;
        this.salary=salary;
    }
    
    public void setName(String name){
        this.name = name;
    }
    
    public String getName(){
        return name;
    }
    
    public void setAge(int age){
        this.age = age;
    }
    
    public int getAge(){
        return age;
    }
    
    public void setSalary(double salary){
        this.salary = salary;
    }
    
    public double getSalary(){
        return salary;
    }
}

public class Main{
    public static void main(String ...a){
        List<Employee> employee = Arrays.asList(new Employee("rajesh",23,23000),new Employee("mohan",21,29000), new Employee("amrita",25,13000) );
        
        double d = employee.stream().filter(s->s.getAge()>20).mapToDouble(s->s.getSalary()).average().orElse(0.0);
        
        System.out.println("Sum of Employee Salary is: " + d);
        
    }
}

Output:

Sum of Employee Salary is: 21666.666666666668

Scenario 2:

Student Grades System

There is a list of students with their (name, grades). We have to find the name of the student who has the highest grade.

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.NoSuchElementException;

class Student {
    private String name;
    private double grades;

    public Student(String name, double grades) {
        this.name = name;
        this.grades = grades;
    }

    public String getName() {
        return name;
    }

    public double getGrades() {
        return grades;
    }
}

public class Main {
    public static void main(String[] args) {
        List<Student> students = new ArrayList<>();
        students.add(new Student("Pawan", 99.0));
        students.add(new Student("Nishant", 82.0));
        students.add(new Student("Charlie", 82.5));
        students.add(new Student("Rob", 88.5));
        students.add(new Student("Daniel", 99.5));

        //else throw null
        Student studentWithHighestGrade1 = students.stream()
                .max(Comparator.comparingDouble(Student::getGrades))
                .orElse(null);
         
        if (studentWithHighestGrade1 != null) {
            System.out.println("(First Method) Student with the highest grade:");
            System.out.println("Name: " + studentWithHighestGrade1.getName());
            System.out.println("Grade: " + studentWithHighestGrade1.getGrades());
        }else{
            System.out.println("No student found.");
        }
        
        //else throw NoSuchElementException
        Student studentWithHighestGrade2 = students.stream()
                .max(Comparator.comparingDouble(Student::getGrades))
                .orElseThrow(NoSuchElementException::new);
         
        if (studentWithHighestGrade2 != null) {
            System.out.println("(Second Method) Student with the highest grade:");
            System.out.println("Name: " + studentWithHighestGrade2.getName());
            System.out.println("Grade: " + studentWithHighestGrade2.getGrades());
        }else{
            System.out.println("No student found.");
        }
        
    }
}

Output

(First Method) Student with the highest grade:
Name: Daniel
Grade: 99.5
(Second Method) Student with the highest grade:
Name: Daniel
Grade: 99.5

Scenario 3:

Product Inventory Management

Suppose in a Product Inventory We have a list of products with (name, price, quantity). You have to calculate the total cost of all products which are in stock.

import java.util.*;

class Product {
    private String name;
    private int quantity;
    private double price;
    

    Product(String name, double price, int quantity) {
        this.name = name;
        this.price = price;
        this.quantity = quantity;
    }

    public String getName() {
        return name;
    }

    public double getPrice() {
        return price;
    }
    
    public int getQuantity() {
        return quantity;
    }
}

public class Main {
    public static void main(String[] args) {
        List<Product> product = new ArrayList<>();
        product.add(new Product("radio", 99.0, 0));
        product.add(new Product("television", 82.0, 3));
        product.add(new Product("earbud", 82.5, 5));
        product.add(new Product("charger", 88.5, 0));
        product.add(new Product("mobile", 99.5, 2));

        //method 1 using sum()
        double totalCost = product.stream().filter(q->q.getQuantity()>0).mapToDouble(p->p.getQuantity()*p.getPrice()).sum();
        System.out.println("Total cost of all instock products = "+ totalCost);
        
        //method 2 using Double::sum
        double totalCost1 = product.stream().filter(q->q.getQuantity()>0).mapToDouble(p->p.getQuantity()*p.getPrice()).reduce(0,Double::sum);
        System.out.println("Total cost of all instock products = "+totalCost1);
        
    }
}

Output

Total cost of all instock products = 857.5
Total cost of all instock products = 857.5

Scenario 4:

Library Management

There are multiple records of books with (title, author, publication year). We have to write Java 8 code to filter all books that were published after 2010.

import java.util.*;
class Book {
    private String title;
    private String author;
    private int publicationYear;

    Book(String title, String author, int publicationYear) {
        this.title = title;
        this.author = author;
        this.publicationYear = publicationYear;
    }

    public String getTitle() {
        return title;
    }

    public String getAuthor() {
        return author;
    }
    
    public int getPublicationYear() {
        return publicationYear;
    }
}

public class Main {
    public static void main(String[] args) {
        List<Book> book = new ArrayList<>();
        book.add(new Book("C Programming","C Author", 2011));
        book.add(new Book("Java Programming","Java Author",2003));
        book.add(new Book("Python Programming","Python Author",2015));
        book.add(new Book("React Programming","React Author", 2000));
        book.add(new Book("C++ Programming","C++ Author", 2002));
        book.stream().filter(b -> b.getPublicationYear()>2010).forEach(b->System.out.println(b.getTitle()));
    }
}

Output

C Programming
Python Programming

Scenario 5:

Data Transformation

Here we are moving to the next topic to see some new concepts of Data Transformation using Java 8. We have Given a list of strings and we have to convert them to uppercase using Java 8 streams.

import java.util.*; 
import java.util.stream.Collectors;
public class UpperCaseConverter {
    public static void main(String[] args) {
        List<String> strings = Arrays.asList("java", "python", "react", "javascript");
        
        //method 1
        List<String> upperCaseString = strings.stream().map(String::toUpperCase).collect(Collectors.toList());
        System.out.println("Output 1:");
        System.out.println(upperCaseString);
        
        
        //method2
        System.out.println("Output 2:");
        strings.stream().map(String::toUpperCase).collect(Collectors.toList()).
                                       forEach(System.out::println);
    }
}

Output

Output 1:
[JAVA, PYTHON, REACT, JAVASCRIPT]
Output 2:
JAVA
PYTHON
REACT
JAVASCRIPT

Scenario 6:

Filtering and Sorting on Data

For the given list of elements, perform Filtering and Sorting on the elements. Write a java 8 program to perform operations like filter out the odd numbers from list and sort the remaining ones in ascending order.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class FilterOddNumberAndSort {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1,34,22,13,55,4,3,87,11,22,12);
        System.out.println("Unsorted Unfiltered List = " + numbers);
        List<Integer> filteredAndSortedNumbers = numbers.stream()
                .filter(n -> n % 2 == 0).sorted()
                .collect(Collectors.toList());
        System.out.println("Sorted Filtered List = " + filteredAndSortedNumbers);
    }
}

Output

Unsorted Unfiltered List = [1, 34, 22, 13, 55, 4, 3, 87, 11, 22, 12]
Sorted Filtered List = [4, 12, 22, 22, 34]

Scenario 7:

Word Count

Perform Word Count for the given paragraph and print the occurrences of each word using a Java Map and Java 8.

import java.util.*;
import java.util.Map;
import java.util.stream.Collectors;
public class WordCountInString {
    public static void main(String[] args) {
        String paragraph = "Her friends always walked hand in hand with her in her difficult times.";
        
        //Method 1
        List<String> stringArray = Arrays.asList(paragraph.toLowerCase().split(" "));
        Map<String, Long> wordCount1= stringArray.stream().collect(Collectors.groupingBy(word->word, Collectors.counting()));
        System.out.println("Output 1:");
        System.out.println(wordCount1);
        
        
        //Method 2
        Map<String, Long> wordCount2= Arrays.stream(paragraph.toLowerCase().split(" "))
                .collect(Collectors.groupingBy(word -> word, Collectors.counting()));
        System.out.println("Output 2:");
        System.out.println(wordCount2);
        
    }
}

Output:

Output 1:
{always=1, with=1, walked=1, times.=1, her=3, in=2, difficult=1, friends=1, hand=2}
Output 2:
{always=1, with=1, walked=1, times.=1, her=3, in=2, difficult=1, friends=1, hand=2}

Scenario 8:

Transaction Management

For the given transaction data with (payer, payee, amount), calculate the total amount received by each payee. Here you have to use the grouping and Summing concept of Java 8.

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

class Transaction {
    private String payer;
    private String payee;
    private double amount;

    public Transaction(String payer, String payee, double amount) {
        this.payer = payer;
        this.payee = payee;
        this.amount = amount;
    }

    public String getPayer() {
        return payer;
    }

    public String getPayee() {
        return payee;
    }

    public double getAmount() {
        return amount;
    }
}

public class TransactionAnalyzer {
    public static void main(String[] args) {
        List<Transaction> transactions = Arrays.asList(
                new Transaction("Dom", "Mona", 120.0),
                new Transaction("Jhon", "Charlie", 150.0),
                new Transaction("Bob", "Reha", 210.0),
                new Transaction("Jhon", "Mona", 150.0)
        );

        // Method 1 using method reference
        Map<String, Double> totalAmountReceivedByPayee1 = transactions.stream()
                .collect(Collectors.groupingBy(Transaction::getPayee, Collectors.summingDouble(Transaction::getAmount)));
        System.out.println(totalAmountReceivedByPayee1);
        
        // Method 2 using method reference
        Map<String, Double> totalAmountReceivedByPayee2 = transactions.stream()
                .collect(Collectors.groupingBy(t -> t.getPayee(), Collectors.summingDouble(t -> t.getAmount())));
        System.out.println(totalAmountReceivedByPayee2);
        
    }
}


Output

{Mona=270.0, Charlie=150.0, Reha=210.0}
{Mona=270.0, Charlie=150.0, Reha=210.0}

Scenario 9:

Stream Chaining

Given a list of strings, filter out the ones containing a specific substring and then concatenate them into a single string.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class StringFilterConcatenator {
    public static void main(String[] args) {
        List<String> string = Arrays.asList("pablo", "laptop", "kiwi", "mouse", "paces");
        String subString = "pa";
        String concatenatedString = string.stream()
                .filter(s -> s.contains(subString))
                .collect(Collectors.joining());
        System.out.println(concatenatedString);
    }
}

Output:

pablopaces

Scenario 10:

Prime number

Print the list of all prime numbers in the given range using Java 8.

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class PrimeNumberProgram {
    public static void main(String[] args) {
        int start = 1;
        int end = 50;
        List<Integer> primeNumbers = generatePrimeNumbers(start, end);
        System.out.println(primeNumbers);
    }

    public static List<Integer> generatePrimeNumbers(int start, int end) {
        return IntStream.rangeClosed(start, end)
                .filter(PrimeNumberProgram::isPrimeNumber)
                .boxed()
                .collect(Collectors.toList());
    }

    public static boolean isPrimeNumber(int number) {
        if (number <= 1) {
            return false;
        }
        for (int i = 2; i <= Math.sqrt(number); i++) {
            if (number % i == 0) {
                return false;
            }
        }
        return true;
    }
}

Output:

[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]

Below is Some problem that you can try to solve on your own. Later we will Provide the solutions But before you can try by yourself.

Scenario 11:

Sales Management

In the retail marketplace, there are multiple transactions that happen from time to time. We have to perform the data analysis over the revenue.

For the Given list of sales transactions (transactionID, productID, quantity, price), you have to find the top N products (by revenue) sold in the last 3 months using Java 8.

Here N is the number of products that you want.

import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

class Transaction {
    private String transactionID;
    private String productID;
    private int quantity;
    private double price;
    private LocalDate transactionDate;
    
    public Transaction(){
        
    }
    public Transaction(String transactionID, String productID, int quantity, double price, LocalDate transactionDate){
        this.transactionID = transactionID;
        this.productID = productID;
        this.quantity = quantity;
        this.price = price;
        this.transactionDate = transactionDate;
    }

    public LocalDate getTransactionDate(){
        return transactionDate;
    }
    
    public String getTransactionID(){
        return transactionID;
    }
    
    public String getProductID(){
        return productID;
    }
    
    public int getQuantity(){
        return quantity;
    }
    
    public double getPrice(){
        return price;
    }

}

public class TopNProductsByRevenue {
    public static void main(String[] args) {
        List<Transaction> salesTransactions = new ArrayList<>(); 
        salesTransactions.add(new Transaction("1","1",10,23.9,LocalDate.now()));
        salesTransactions.add(new Transaction("2","1",11,21.9,LocalDate.now()));
        salesTransactions.add(new Transaction("3","2",12,21.9,LocalDate.now()));
        salesTransactions.add(new Transaction("4","3",11,24.9,LocalDate.now()));
        salesTransactions.add(new Transaction("5","3",4,23.9,LocalDate.now()));
        salesTransactions.add(new Transaction("6","3",5,26.9,LocalDate.now()));
        salesTransactions.add(new Transaction("7","2",6,27.9,LocalDate.now()));
        salesTransactions.add(new Transaction("8","1",12,28.9,LocalDate.now()));
        
        int N = 2; // Number of top products
        
        LocalDate threeMonthsAgo = LocalDate.now().minusMonths(3);
        
        Map<String, Double> productRevenueMap = salesTransactions.stream()
            .filter(transaction -> transaction.getTransactionDate().isAfter(threeMonthsAgo))
            .collect(Collectors.groupingBy(
                Transaction::getProductID,
                Collectors.summingDouble(transaction -> transaction.getPrice() * transaction.getQuantity())
            ));
        
        List<Map.Entry<String, Double>> sortedProductsByRevenue = productRevenueMap.entrySet().stream()
            .sorted((entry1, entry2) -> entry2.getValue().compareTo(entry1.getValue()))
            .limit(N)
            .collect(Collectors.toList());
        
        System.out.println("Top " + N + " products by revenue in the last 3 months:");
        for (Map.Entry<String, Double> entry : sortedProductsByRevenue) {
            System.out.println("ProductID: " + entry.getKey() + ", Revenue: " + entry.getValue());
        }
    }
}

Output

Top 2 products by revenue in the last 3 months:
ProductID: 1, Revenue: 826.6999999999999
ProductID: 3, Revenue: 504.0

Scenario 12:

Employee Management System

Given Employee details, you have to sort the employee details on basis of employees name using java 8.

import java.util.ArrayList;
import java.util.List;
import java.util.Comparator;
import java.util.stream.Collectors;

class Employee {
    private int id;
    private String name;
    private int age;

    public Employee(int id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

}

public class EmployeeSorting {
    public static void main(String[] args) {
        List<Employee> employees = new ArrayList<>();
        employees.add(new Employee(1, "Mohan", 30));
        employees.add(new Employee(2, "Sohan", 25));
        employees.add(new Employee(3, "Rohan", 28));
        
        // Sorting employee based on names using Java 8 streams
        List<Employee> sortedEmployees = employees.stream()
                .sorted(Comparator.comparing(Employee::getName))
                .collect(Collectors.toList());

        // Printing sorted employee details
        sortedEmployees.forEach(s->System.out.println(s.getName()));
    }
}

Output

Mohan
Rohan
Sohan