Top 25 Java 8 Coding Interview questions suitable for candidates with 3+ years of experience

List of Top 25 Java 8 Coding Interview questions suitable for candidates with 3+ years of experience

Coding questions focus on utilizing the features introduced in Java 8, such as lambda expressions, functional interfaces, and the Stream API. By practicing these questions, you'll become more comfortable with functional programming concepts and enhance your Java 8 programming skills.

1. Write a program to find the sum of all elements in a list using the Stream API.

      
package com.tech.eyes.world4u;

import java.util.Arrays;
import java.util.List;

public class SumOfElements {

	public static void main(String[] args) {

		/**
		 * Write a program to find the sum of all elements in a list using the Stream API.
		 */
		
		List elements = Arrays.asList(2,5,7,9,6,5,4);
		
		int sumOfElements = elements.stream()
				.mapToInt(Integer::intValue)
				.sum();
		System.out.println("Sum of all elements: "+sumOfElements);
	}
}

Output: Sum of all elements: 38
      
    

In this program, we create a list of integers using Arrays.asList() with the values 2,5,7,9,6,5 and 4.

Then, we use the stream() method to convert the list into a stream of elements.

Next, we use the mapToInt() method to convert each element from Integer type to int type.

This step is necessary because the sum() method is available for streams of primitive types such as IntStream.

Finally, we call the sum() method on the stream to calculate the sum of all elements. The result is stored in the sum variable, and we print it to the console.

2. Write a program to remove duplicate elements from a list using the Stream API

      
package com.tech.eyes.world4u;	  

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

public class RemoveDuplicatesExample {
    public static void main(String[] args) {
        List numbers = new ArrayList<>(List.of(1, 2, 2, 3, 4, 4, 5, 5));

        List uniqueNumbers = numbers.stream()
                .distinct()
                .collect(Collectors.toList());

        System.out.println("Original numbers: " + numbers);
        System.out.println("Unique numbers: " + uniqueNumbers);
    }
}

Output:	
Original numbers: [1, 2, 2, 3, 4, 4, 5, 5]
Unique numbers: [1, 2, 3, 4, 5]

      
    

In this program, we start with a list called numbers that contains duplicate elements.

We use the stream() method on the list to create a stream of elements.

Then, we apply the distinct() method on the stream to remove duplicate elements and obtain a stream of unique elements.

Finally, we collect the unique elements into a new list using the collect() method with Collectors.toList().

The resulting list, uniqueNumbers, will only contain the distinct elements from the original list.

3. Write a program to sort a list of strings in descending order of length using the Stream API.

      
package com.tech.eyes.world4u;	
  
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public class SortStringsByLengthExample {
    public static void main(String[] args) {
        List strings = Arrays.asList("apple", "banana", "orange", "kiwi", "strawberry");

        List sortedList = strings.stream()
                .sorted(Comparator.comparingInt(String::length).reversed())
                .toList();

        System.out.println("Original List: " + strings);
        System.out.println("Sorted List (descending order of length): " + sortedList);
    }
}

Output:	
Original List: [apple, banana, orange, kiwi, strawberry]
Sorted List (descending order of length): [strawberry, banana, orange, apple, kiwi]
      
    

In this program, we have a list of strings called strings containing several fruits.

We use the stream() method to create a stream of strings from the list.

Then, we apply the sorted() method on the stream, passing a comparator that compares the length of strings using Comparator.comparingInt(String::length).

The reversed() method is used to sort the strings in descending order of length.

Finally, we collect the sorted strings into a new list using the toList() method.

The program prints the original list and the sorted list to the console, showing that the strings are sorted in descending order of length.

4. Write a program to find the average of a list of integers using the Stream API.

      
package com.tech.eyes.world4u;	
  
import java.util.Arrays;
import java.util.List;
import java.util.OptionalDouble;

public class AverageOfIntegersExample {
    public static void main(String[] args) {
        List numbers = Arrays.asList(5, 10, 15, 20, 25);

        OptionalDouble average = numbers.stream()
                .mapToDouble(Integer::doubleValue)
                .average();

        if (average.isPresent()) {
            System.out.println("Numbers: " + numbers);
            System.out.println("Average: " + average.getAsDouble());
        } else {
            System.out.println("No numbers found in the list.");
        }
    }
}

Output:
Numbers: [5, 10, 15, 20, 25]
Average: 15.0

      
    

In this program, we have a list of integers called numbers containing several values. We use the stream() method to create a stream of integers from the list.

Then, we use the mapToDouble() method to convert each integer value to a double value, as the average() method expects a stream of doubles.

By mapping each integer to a double, we can calculate the average more accurately.

Next, we call the average() method on the stream to calculate the average of the numbers.

The average() method returns an OptionalDouble, which may or may not contain the average value.

We use an if statement to check if the average is present (average.isPresent()). If it is present, we print the original list of numbers and the calculated average to the console using average.getAsDouble(). If the average is not present, it means the list was empty, and we print a message indicating that no numbers were found in the list.

5. Write a program to convert a list of strings to uppercase using the Stream API.

      
package com.tech.eyes.world4u;	  

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

public class ConvertToUppercaseExample {
    public static void main(String[] args) {
        List strings = Arrays.asList("apple", "banana", "orange", "kiwi", "strawberry");

        List uppercaseList = strings.stream()
                .map(String::toUpperCase)
                .collect(Collectors.toList());

        System.out.println("Original List: " + strings);
        System.out.println("Uppercase List: " + uppercaseList);
    }
}

Output:
Original List: [apple, banana, orange, kiwi, strawberry]
Uppercase List: [APPLE, BANANA, ORANGE, KIWI, STRAWBERRY]

      
    

In this program, we have a list of strings called strings containing various lowercase words.

We use the stream() method to create a stream of strings from the list.

Then, we apply the map() method on the stream, using the String::toUpperCase method reference to convert each string to uppercase.

Finally, we collect the uppercase strings into a new list using the collect() method with Collectors.toList().

6. Write a program to count the number of words in a string using the Stream API.

      
package com.tech.eyes.world4u;	  


public class CountWordsExample {
    public static void main(String[] args) {
        String sentence = "The quick brown fox jumps over the lazy dog";

        long wordCount = countWords(sentence);

        System.out.println("Sentence: " + sentence);
        System.out.println("Number of Words: " + wordCount);
    }

    public static long countWords(String sentence) {
        return Stream.of(sentence.trim().split("\\s+"))
                .filter(word -> !word.isEmpty())
                .count();
    }
}

Output:
Sentence: The quick brown fox jumps over the lazy dog
Number of Words: 9

      
    

In this program, we define a countWords() method that takes a string sentence as input and returns the count of words in the sentence.

Within the countWords() method, we use the Stream API to count the words. Here's the breakdown of the steps:

We start by trimming the input sentence using sentence.trim() to remove any leading or trailing whitespace.

Next, we split the trimmed sentence into words using the regular expression \\s+, which matches one or more whitespace characters. This creates an array of words.

We convert the array of words into a stream using Stream.of().

We apply a filter operation to the stream, excluding any empty words using filter(word -> !word.isEmpty()).

Finally, we call the count() method on the stream to count the number of words.

7. Write a program to find the maximum and minimum elements in a list using the Stream API.

      
package com.tech.eyes.world4u;	  


import java.util.Arrays;
import java.util.List;
import java.util.Optional;

public class MaxMinElementsExample {
    public static void main(String[] args) {
        List numbers = Arrays.asList(5, 10, 15, 20, 25);

        Optional maxElement = numbers.stream()
                .max(Integer::compare);

        Optional minElement = numbers.stream()
                .min(Integer::compare);

        if (maxElement.isPresent() && minElement.isPresent()) {
            System.out.println("Numbers: " + numbers);
            System.out.println("Maximum Element: " + maxElement.get());
            System.out.println("Minimum Element: " + minElement.get());
        } else {
            System.out.println("No numbers found in the list.");
        }
    }
}

Output:
Numbers: [5, 10, 15, 20, 25]
Maximum Element: 25
Minimum Element: 5

      
    

In this program, we have a list of integers called numbers containing several values.

We use the stream() method to create a stream of integers from the list.

To find the maximum element, we use the max() method on the stream, passing Integer::compare as the comparator.

The max() method returns an Optional that may or may not contain the maximum element.

Similarly, to find the minimum element, we use the min() method on the stream, also passing Integer::compare as the comparator.

The min() method returns an Optional that may or may not contain the minimum element.

We use if statements to check if the maximum and minimum elements are present (maxElement.isPresent() and minElement.isPresent()).

If they are present, we retrieve their values using maxElement.get() and minElement.get()

If either the maximum or minimum element is not present, it means the list was empty, and we print a message indicating that no numbers were found in the list.

8. Write a program to concatenate all strings in a list using the Stream API.

      
package com.tech.eyes.world4u;	  


import java.util.Arrays;
import java.util.List;

public class ConcatenateStringsExample {
    public static void main(String[] args) {
        List strings = Arrays.asList("Hello", " ", "World", "!");

        String concatenatedString = strings.stream()
                .reduce("", String::concat);

        System.out.println("Strings: " + strings);
        System.out.println("Concatenated String: " + concatenatedString);
    }
}

Output:
Strings: [Hello,  , World, !]
Concatenated String: Hello World!

      
    

In this program, we have a list of strings called strings containing several values. We use the stream() method to create a stream of strings from the list.

Then, we use the reduce() method on the stream to concatenate all the strings.

We start with an empty string "" as the identity value and use the String::concat method reference to concatenate each string in the stream to the accumulated result.

The reduce() method applies the concatenation operation to all strings in the stream, resulting in a single concatenated string.

9. Write a program to filter out even numbers from a list using the Stream API.

      
package com.tech.eyes.world4u;	  

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

public class FilterEvenNumbersExample {
    public static void main(String[] args) {
        List numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

        List evenNumbers = numbers.stream()
                .filter(number -> number % 2 == 0)
                .collect(Collectors.toList());

        System.out.println("Numbers: " + numbers);
        System.out.println("Even Numbers: " + evenNumbers);
    }
}


Output:
Numbers: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Even Numbers: [2, 4, 6, 8, 10]

      
    

In this program, we have a list of integers called numbers containing several values.

We use the stream() method to create a stream of integers from the list.

Then, we apply the filter() method on the stream, passing a lambda expression number -> number % 2 == 0 as the predicate.

This filters out only the even numbers from the stream based on the condition that the number modulo 2 equals 0.

Finally, we collect the filtered even numbers into a new list using the collect() method with Collectors.toList().

10. Write a program to check if all elements in a list satisfy a given condition using the Stream API.

      
package com.tech.eyes.world4u;	  

import java.util.Arrays;
import java.util.List;

public class CheckAllElementsExample {
    public static void main(String[] args) {
        List numbers = Arrays.asList(2, 4, 6, 8, 10);

        boolean allEven = numbers.stream()
                .allMatch(number -> number % 2 == 0);

        System.out.println("Numbers: " + numbers);
        System.out.println("All even: " + allEven);
    }
}

Output:
Numbers: [2, 4, 6, 8, 10]
All even: true

      
    

In this program, we have a list of integers called numbers containing several values. We use the stream() method to create a stream of integers from the list.

Then, we use the allMatch() method on the stream, passing a lambda expression number -> number % 2 == 0 as the predicate.

This checks if all elements in the stream satisfy the condition that the number modulo 2 equals 0, which determines if they are even.

The allMatch() method returns a boolean value indicating whether all elements in the stream satisfy the condition.

Finally, we print the original list of numbers and the result of the allMatch() operation to the console, which indicates whether all elements in the list are even.

11. Write a program to find the distinct elements in a list using the Stream API.

      
package com.tech.eyes.world4u;	  

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

public class DistinctElementsExample {
    public static void main(String[] args) {
        List numbers = Arrays.asList(1, 2, 3, 2, 4, 3, 5, 6, 5, 4);

        List distinctNumbers = numbers.stream()
                .distinct()
                .collect(Collectors.toList());

        System.out.println("Numbers: " + numbers);
        System.out.println("Distinct Numbers: " + distinctNumbers);
    }
}


Output:
Numbers: [1, 2, 3, 2, 4, 3, 5, 6, 5, 4]
Distinct Numbers: [1, 2, 3, 4, 5, 6]

      
    

In this program, we have a list of integers called numbers containing several values, including duplicates.

We use the stream() method to create a stream of integers from the list.

Then, we apply the distinct() method on the stream to filter out the duplicate elements and keep only the distinct elements.

Finally, we collect the distinct elements into a new list using the collect() method with Collectors.toList().

The program prints the original list of numbers and the list of distinct numbers to the console, showing that the duplicate elements have been removed.

12. Write a program to convert a list of integers to a comma-separated string using the Stream API.

      
package com.tech.eyes.world4u;	  

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

public class ConvertToStringExample {
    public static void main(String[] args) {
        List numbers = Arrays.asList(1, 2, 3, 4, 5);

        String commaSeparatedString = numbers.stream()
                .map(String::valueOf)
                .collect(Collectors.joining(", "));

        System.out.println("Numbers: " + numbers);
        System.out.println("Comma-Separated String: " + commaSeparatedString);
    }
}

Output:
Numbers: [1, 2, 3, 4, 5]
Comma-Separated String: 1, 2, 3, 4, 5

      
    

In this program, we have a list of integers called numbers containing several values. We use the stream() method to create a stream of integers from the list.

Then, we use the map() method on the stream, passing String::valueOf as the mapping function. This converts each integer element to a string representation.

Next, we collect the string representations into a single string using the collect() method with Collectors.joining(", "). This joins the elements with a comma and space as the delimiter.

13. Write a program to find the square of each element in a list using the Stream API.

      
package com.tech.eyes.world4u;	  

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

public class SquareElementsExample {
    public static void main(String[] args) {
        List numbers = Arrays.asList(1, 2, 3, 4, 5);

        List squares = numbers.stream()
                .map(number -> number * number)
                .collect(Collectors.toList());

        System.out.println("Numbers: " + numbers);
        System.out.println("Squares: " + squares);
    }
}

Output:
Numbers: [1, 2, 3, 4, 5]
Squares: [1, 4, 9, 16, 25]

      
    

In this program, we have a list of integers called numbers containing several values.

We use the stream() method to create a stream of integers from the list.

Then, we use the map() method on the stream, passing a lambda expression number -> number * number as the mapping function. This squares each element in the stream by multiplying it with itself.

Finally, we collect the squared elements into a new list using the collect() method with Collectors.toList().

14. Write a program to group a list of objects by a specific attribute using the Stream API.

      
package com.tech.eyes.world4u;	  

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

class Person {
    private String name;
    private int age;

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

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

public class GroupByAttributeExample {
    public static void main(String[] args) {
        List persons = Arrays.asList(
                new Person("Alice", 25),
                new Person("Bob", 30),
                new Person("Charlie", 25),
                new Person("David", 30),
                new Person("Eve", 25)
        );

        Map> groupedByAge = persons.stream()
                .collect(Collectors.groupingBy(Person::getAge));

        System.out.println("Persons: " + persons);
        System.out.println("Grouped by Age: " + groupedByAge);
    }
}


Output:
Persons: [Person{name='Alice', age=25}, Person{name='Bob', age=30}, Person{name='Charlie', age=25}, Person{name='David', age=30}, Person{name='Eve', age=25}]
Grouped by Age: {25=[Person{name='Alice', age=25}, Person{name='Charlie', age=25}, Person{name='Eve', age=25}], 30=[Person{name='Bob', age=30}, Person{name='David', age=30}]}

      
    

In this program, we have a class Person with attributes name and age. We create a list of Person objects called persons with different names and ages.

We use the stream() method to create a stream of Person objects from the list.

Then, we use the collect() method with Collectors.groupingBy() to group the Person objects by their age. We pass Person::getAge as the grouping function, which extracts the age attribute from each Person object.

The result is a Map> where the keys are the distinct ages and the values are lists of Person objects with that age.

Finally, we print the original list of persons and the grouped map to the console.

15. Write a program to find the longest string in a list using the Stream API.

      
package com.tech.eyes.world4u;	  

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

public class LongestStringExample {
    public static void main(String[] args) {
        List strings = Arrays.asList("apple", "banana", "cherry", "dragonfruit", "elderberry");

        Optional longestString = strings.stream()
                .max((s1, s2) -> s1.length() - s2.length());

        if (longestString.isPresent()) {
            System.out.println("Strings: " + strings);
            System.out.println("Longest String: " + longestString.get());
        } else {
            System.out.println("No strings found.");
        }
    }
}

Output:
Strings: [apple, banana, cherry, dragonfruit, elderberry]
Longest String: dragonfruit

      
    

In this program, we have a list of strings called strings containing several values. We use the stream() method to create a stream of strings from the list.

Then, we use the max() method on the stream, passing a lambda expression (s1, s2) -> s1.length() - s2.length() as the comparator. This compares the strings based on their lengths, allowing us to find the longest string.

The max() method returns an Optional that either contains the longest string or is empty if the list is empty.

Finally, we check if the longest string is present using isPresent(), and if so, we print the original list of strings and the longest string to the console using get().

16. Write a program to convert a list of strings to a map where the string is the key and its length is the value using the Stream API.

      
package com.tech.eyes.world4u;	  

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

public class ConvertToMapExample {
    public static void main(String[] args) {
        List strings = Arrays.asList("apple", "banana", "cherry", "dragonfruit");

        Map stringLengthMap = strings.stream()
                .collect(Collectors.toMap(
                        str -> str,
                        String::length
                ));

        System.out.println("Strings: " + strings);
        System.out.println("String Length Map: " + stringLengthMap);
    }
}


Output:
Strings: [apple, banana, cherry, dragonfruit]
String Length Map: {apple=5, banana=6, cherry=6, dragonfruit=11}

      
    

In this program, we have a list of strings called strings containing several values.We use the stream() method to create a stream of strings from the list.

Then, we use the collect() method with Collectors.toMap() to collect the strings into a map. We provide two mapping functions:

  • The first function str -> str specifies that the string itself should be used as the key.
  • The second function String::length specifies that the length of the string should be used as the value.
  • The resulting map has the strings as keys and their lengths as values.

17. Write a program to find the first element in a list that satisfies a given condition using the Stream API.

      
package com.tech.eyes.world4u;	  

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

public class FindFirstExample {
    public static void main(String[] args) {
        List numbers = Arrays.asList(1, 2, 3, 4, 5);

        Optional firstEvenNumber = numbers.stream()
                .filter(number -> number % 2 == 0)
                .findFirst();

        if (firstEvenNumber.isPresent()) {
            System.out.println("Numbers: " + numbers);
            System.out.println("First Even Number: " + firstEvenNumber.get());
        } else {
            System.out.println("No even number found.");
        }
    }
}


Output:
Numbers: [1, 2, 3, 4, 5]
First Even Number: 2

      
    

In this program, we have a list of integers called numbers containing several values. We use the stream() method to create a stream of integers from the list.

Then, we use the filter() method on the stream to filter out the elements that satisfy the condition. In this case, we filter for numbers that are even using the condition number -> number % 2 == 0.

Next, we use the findFirst() method to retrieve the first element in the stream that satisfies the condition.

The findFirst() method returns an Optional that either contains the first element or is empty if no element satisfies the condition.

Finally, we check if the first even number is present using isPresent(), and if so, we print the original list of numbers and the first even number to the console using get().

18. Write a program to calculate the sum of squares of even numbers in a list using the Stream API.

      
package com.tech.eyes.world4u;	  

import java.util.Arrays;
import java.util.List;

public class SumOfSquaresOfEvenNumbersExample {
    public static void main(String[] args) {
        List numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

        int sumOfSquares = numbers.stream()
                .filter(n -> n % 2 == 0) // Filter even numbers
                .mapToInt(n -> n * n) // Square each number
                .sum(); // Calculate the sum

        System.out.println("Sum of squares of even numbers: " + sumOfSquares);
    }
}

Output:
Sum of squares of even numbers: 220

      
    

In this program, we have a list of numbers. We use the Stream API to perform the following operations:

  • 1. filter - We filter the numbers to keep only the even numbers using the condition n % 2 == 0.
  • 2. mapToInt - We square each even number using the mapping operation n -> n * n.
  • 3. sum - We calculate the sum of the squared even numbers.

19. Write a program to find the average length of strings in a list using the Stream API.

      
package com.tech.eyes.world4u;	  

import java.util.Arrays;
import java.util.List;

public class AverageStringLengthExample {
    public static void main(String[] args) {
        List strings = Arrays.asList("apple", "banana", "cherry", "dragonfruit");

        double averageLength = strings.stream()
                .mapToInt(String::length)
                .average()
                .orElse(0.0);

        System.out.println("Strings: " + strings);
        System.out.println("Average Length: " + averageLength);
    }
}


Output:
Strings: [apple, banana, cherry, dragonfruit]
Average Length: 7.5

      
    

In this program, we have a list of strings called strings containing several values. We use the stream() method to create a stream of strings from the list.

Then, we use the mapToInt() method on the stream to convert each string to its length as an integer.

Next, we use the average() method to calculate the average of the lengths.

The average() method returns an OptionalDouble that either contains the average value or is empty if the stream is empty.

Finally, we retrieve the average length using orElse(0.0), which returns 0.0 if the optional is empty.

20. Implement a program that finds the 2nd and 3rd highest salary from a list of Employee objects.

      
package com.tech.eyes.world4u;	  

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

class Employee {
    private String name;
    private double salary;

    public Employee(String name, double salary) {
        this.name = name;
        this.salary = salary;
    }

    public String getName() {
        return name;
    }

    public double getSalary() {
        return salary;
    }
}

public class FindSecondAndThirdHighestSalaryExample {
    public static void main(String[] args) {
        List employees = new ArrayList<>();
        employees.add(new Employee("Alice", 50000.0));
        employees.add(new Employee("Bob", 70000.0));
        employees.add(new Employee("Charlie", 90000.0));
        employees.add(new Employee("David", 60000.0));
        employees.add(new Employee("Eve", 80000.0));

        // Sort the employees by salary in descending order
        Collections.sort(employees, Comparator.comparing(Employee::getSalary).reversed());

        if (employees.size() >= 3) {
            Employee secondHighest = employees.get(1);
            Employee thirdHighest = employees.get(2);

            System.out.println("Employees: " + employees);
            System.out.println("Second Highest Salary: " + secondHighest.getSalary());
            System.out.println("Third Highest Salary: " + thirdHighest.getSalary());
        } else {
            System.out.println("Insufficient number of employees.");
        }
    }
}


Output:
Employees: [Employee{name='Charlie', salary=90000.0}, Employee{name='Eve', salary=80000.0}, Employee{name='Bob', salary=70000.0}, Employee{name='David', salary=60000.0}, Employee{name='Alice', salary=50000.0}]
Second Highest Salary: 80000.0
Third Highest Salary: 70000.0

      
    

In this program, we have a class Employee with attributes name and salary. We create a list of Employee objects called employees with different names and salaries.

We sort the list of employees in descending order based on their salary using the Collections.sort() method and a custom comparator that compares the salaries.

If the list has at least 3 employees, we retrieve the second and third elements (indexes 1 and 2) using get().

21. Implement a program that sorts a list of Employee objects based on their Employee ID in ascending order.

      
package com.tech.eyes.world4u;	  

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

public class SortEmployeesByIDExample {
    public static void main(String[] args) {
        List employees = new ArrayList<>();
        employees.add(new Employee(103, "John"));
        employees.add(new Employee(101, "Alice"));
        employees.add(new Employee(105, "Bob"));
        employees.add(new Employee(102, "Eve"));

        System.out.println("Before sorting:");
        for (Employee employee : employees) {
            System.out.println(employee);
        }

        Collections.sort(employees, Comparator.comparingInt(Employee::getId));

        System.out.println("\nAfter sorting:");
        for (Employee employee : employees) {
            System.out.println(employee);
        }
    }
}

class Employee {
    private int id;
    private String name;

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

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}

Output:
Before sorting:
Employee{id=103, name='John'}
Employee{id=101, name='Alice'}
Employee{id=105, name='Bob'}
Employee{id=102, name='Eve'}

After sorting:
Employee{id=101, name='Alice'}
Employee{id=102, name='Eve'}
Employee{id=103, name='John'}
Employee{id=105, name='Bob'}

      
    

In this program, we have a Employee class that represents an employee with an ID and a name. The Employee class implements the Comparable interface to define the natural ordering based on the employee ID.

The SortEmployeesByIDExample class demonstrates how to sort a list of Employee objects based on their employee ID in ascending order.

We create a list of Employee objects, add some employees to the list, and then use Collections.sort method with a custom Comparator that compares the employee IDs using the comparingInt method.

The Comparator.comparingInt(Employee::getId) specifies that the sorting should be based on the employee IDs. Finally, we print the list before and after sorting to verify the result.

22. Implement a program that sorts a list of Employee objects based on their Employee ID and age in descending order.

      
package com.tech.eyes.world4u;	  

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

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 int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

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

public class SortEmployeeListExample {
    public static void main(String[] args) {
        List employees = new ArrayList<>();
        employees.add(new Employee(3, "Alice", 25));
        employees.add(new Employee(2, "Bob", 30));
        employees.add(new Employee(1, "Charlie", 28));
        employees.add(new Employee(4, "David", 22));

        // Sort the employees by ID and age in descending order
        Collections.sort(employees, Comparator.comparingInt(Employee::getId).reversed()
                .thenComparingInt(Employee::getAge).reversed());

        System.out.println("Sorted Employees:");
        for (Employee employee : employees) {
            System.out.println(employee);
        }
    }
}


Output:
Sorted Employees:
Employee{id=4, name='David', age=22}
Employee{id=3, name='Alice', age=25}
Employee{id=2, name='Bob', age=30}
Employee{id=1, name='Charlie', age=28}

      
    

In this program, we have a class Employee with attributes id, name, and age. We create a list of Employee objects called employees with different IDs, names, and ages.

We sort the list of employees in descending order based on their ID using the Comparator.comparingInt() method and the reversed() method to sort in descending order.

If two employees have the same ID, we further sort them based on their age in descending order using the thenComparingInt() method and the reversed() method.

Finally, we print the sorted list of employees to the console using a for-each loop.

23. Write a program to merge two sorted arrays into a single sorted array without using any additional space.

      
package com.tech.eyes.world4u;	  

public class MergeSortedArraysExample {
    public static void main(String[] args) {
        int[] arr1 = {1, 3, 5, 7, 9};
        int[] arr2 = {2, 4, 6, 8, 10};

        mergeArrays(arr1, arr2);

        System.out.println("Merged Array:");
        for (int num : arr1) {
            System.out.print(num + " ");
        }
        for (int num : arr2) {
            System.out.print(num + " ");
        }
    }

    public static void mergeArrays(int[] arr1, int[] arr2) {
        int n = arr1.length;
        int m = arr2.length;

        for (int i = m - 1; i >= 0; i--) {
            int last = arr1[n - 1];
            int j;

            for (j = n - 2; j >= 0 && arr1[j] > arr2[i]; j--) {
                arr1[j + 1] = arr1[j];
            }

            if (j != n - 2 || last > arr2[i]) {
                arr1[j + 1] = arr2[i];
                arr2[i] = last;
            }
        }
    }
}


Output:
Merged Array:
1 2 3 4 5 6 7 8 9 10

      
    

In this program, we have two sorted arrays, arr1 and arr2. We merge arr2 into arr1 in a way that maintains the sorted order.

We start by iterating over arr2 in reverse order. For each element in arr2, we compare it with the elements in arr1 from right to left until we find the correct position to insert it.

To insert an element from arr2 into arr1, we shift all greater elements in arr1 to the right. We also keep track of the last element in arr1 since it might be displaced during the shifting.

Once we find the correct position, we insert the element from arr2 into arr1, and place the last element of arr1 into the correct position in arr2.

Finally, we print the merged array by traversing both arr1 and arr2.

Note that this approach modifies the original arrays arr1 and arr2 directly, without using any additional space.

24. Validate Special Characters in a String  OR Implement a program that checks whether a given string contains any special characters or not. Special characters are defined as any character that is not a letter (uppercase or lowercase) or a digit (0-9).

      
package com.tech.eyes.world4u;	  

public class CheckSpecialCharactersExample {
    public static void main(String[] args) {
        String str1 = "Hello123";
        String str2 = "Hello#123";

        boolean containsSpecialChars1 = containsSpecialCharacters(str1);
        boolean containsSpecialChars2 = containsSpecialCharacters(str2);

        System.out.println("String 1: " + str1);
        System.out.println("Contains Special Characters? " + containsSpecialChars1);

        System.out.println("String 2: " + str2);
        System.out.println("Contains Special Characters? " + containsSpecialChars2);
    }

    public static boolean containsSpecialCharacters(String str) {
        String specialChars = "[^a-zA-Z0-9]";
        return str.matches(".*" + specialChars + ".*");
    }
}



Output:
String 1: Hello123
Contains Special Characters? false
String 2: Hello#123
Contains Special Characters? true

      
    

In this program, we have a method called containsSpecialCharacters that takes a string str as input and checks if it contains any special characters.

We define a regular expression pattern specialChars that matches any character that is not a letter (uppercase or lowercase) or a digit (0-9).

We then use the matches method on the input string str to check if it matches the pattern of containing any special characters. The matches method returns true if the string matches the pattern, and false otherwise.

Finally, we print the original strings along with whether they contain any special characters or not.

You can modify the strings str1 and str2 to test different cases.

Note that this program considers special characters as any character that is not a letter or a digit, as per the definition provided.

25. Cross-Site Scripting (XSS) Prevention OR Implement a program that demonstrates how to prevent cross-site scripting (XSS) vulnerabilities in Java web applications. Assume you have a web application that allows users to submit comments, and you need to sanitize the user input to prevent any malicious scripts from being executed.

To prevent cross-site scripting (XSS) vulnerabilities in Java web applications, it's important to sanitize user input before displaying it on web pages. One commonly used approach is to use an HTML sanitizer library that can sanitize the input and remove any potentially harmful HTML or JavaScript code.

Here's an example using the OWASP Java HTML Sanitizer library:

1. Add the OWASP Java HTML Sanitizer library to your project. You can download the library from the OWASP website or include it as a dependency in your build file (e.g., Maven or Gradle).

2. In your Java web application, when receiving user input (e.g., comment text), sanitize it using the OWASP HTML Sanitizer before storing it in your data storage:

      
	  
package com.tech.eyes.world4u;	  


import org.owasp.html.PolicyFactory;
import org.owasp.html.Sanitizers;

public class CommentService {
    private PolicyFactory sanitizer;

    public CommentService() {
        // Create a sanitizer policy using OWASP HTML Sanitizer
        sanitizer = Sanitizers.BLOCKS.and(Sanitizers.FORMATTING).and(Sanitizers.LINKS);
    }

    public void saveComment(String commentText) {
        // Sanitize the user input
        String sanitizedText = sanitizer.sanitize(commentText);

        // Save the sanitized comment text to your data storage
        // ...
    }
}
      
    

When displaying the comments on web pages, ensure that you use proper output encoding to prevent the browser from interpreting the sanitized input as HTML or JavaScript code:

      
	  public class CommentController {
    private CommentService commentService;

    public CommentController() {
        commentService = new CommentService();
    }

    // Assuming this is a request handler method for saving a comment
    public void saveComment(String commentText) {
        // Save the comment
        commentService.saveComment(commentText);

        // Redirect or display a success message
        // ...
    }

    // Assuming this is a request handler method for displaying comments
    public String getComments() {
        // Retrieve the comments from your data storage
        List comments = commentService.getComments();

        // Iterate over the comments and properly encode the comment text
        StringBuilder htmlBuilder = new StringBuilder();
        for (Comment comment : comments) {
            String encodedCommentText = encodeHTML(comment.getText());
            htmlBuilder.append("
").append(encodedCommentText).append("
"); } // Return the HTML representation of the comments return htmlBuilder.toString(); } private String encodeHTML(String input) { return input.replace("&", "&") .replace("<", "<") .replace(">", ">") .replace("\"", """) .replace("'", "'"); } }

In this example, the CommentService class demonstrates how to sanitize user input using the OWASP HTML Sanitizer library. The saveComment method sanitizes the input using the created sanitizer policy and saves the sanitized comment text to your data storage.

The CommentController class demonstrates how to properly encode the comment text when displaying it on web pages. The getComments method retrieves the comments from your data storage and iterates over them, properly encoding the comment text using a custom encodeHTML method.

By sanitizing user input and properly encoding output, you can help prevent cross-site scripting vulnerabilities in your Java web application.

These coding questions focus on utilizing the features introduced in Java 8, such as lambda expressions, functional interfaces, and the Stream API. By practicing these questions, you'll become more comfortable with functional programming concepts and enhance your Java 8 programming skills.

Post a Comment

Previous Post Next Post