Thursday, March 30, 2023

Java 8 Coding Interview Questions : 2023 | Part-1

In a Java8 coding interview, candidates are typically asked to write code that utilizes streams, lambdas, or functional interfaces to solve a given problem. The interviewer may also ask questions to test the candidate's knowledge of these features, such as how they work, when to use them, and their benefits compared to traditional Java code.

During the interview, candidates should approach the problem systematically and demonstrate their thought process by explaining their approach as they go along. This can help the interviewer understand the candidate's thought process and make suggestions or corrections if necessary. It is also important to test the code thoroughly and handle any errors or exceptions that may occur.

In this article we discuss about frequently ask Java8 Coding Interview Questions With Explanation.

Java 8 Coding Interview Questions : 2023 | Part-1




Java 8 Coding Interview Questions Part-1

1.Write a Program that calculates the sum of integers from 1 to 10 using Java8.


import java.util.stream.IntStream; 
public class Java8Example
public static void main(String[] args)
int sum = IntStream.rangeClosed(1, 10) .sum(); 
 System.out.("Sum of integers from 1 to 10 is: " + sum); 
 } 
}


Explanation:

  1. import java.util.stream.IntStream;: Import the IntStream class from the java.util.stream package, which provides a sequence of primitive int values.
  2. public class Java8Example: Declare a public class called Java8Example.
  3. public static void main(String[] args): Declare the main method, which is the entry point of the program.
  4. int sum = IntStream.rangeClosed(1, 10).sum();: Create an IntStream of integers from 1 to 10 using the rangeClosed method, and then calculate the sum of all integers using the sum method.
  5. System.out.println("Sum of integers from 1 to 10 is: " + sum);: Print the result of the sum to the console.

2.Write a Program Count the Number of Vowels.



public class Example2 { 
public static void main(String[] args)
// Initialize the string to count vowels 
String str = "Hello, World!"
// Initialize a list of vowels
List<Character> vowels = Arrays.asList('a', 'e', 'i', 'o', 'u'); 
// Convert the string to lowercase and create a list of characters 
 List<Character> characters = str.toLowerCase().chars() .mapToObj(c -> (char) c) .collect(Collectors.toList()); 
// Use Java 8 stream to filter the list and count the number of vowels 
long count = characters.stream() .filter(c -> vowels.contains(c)) .count(); 
// Print the result
System.out.println("The string \"" + str + "\" contains " + count + " vowels."); 
 } 
}

Explanation:

  1. String str = "Hello, World!"; initializes a string variable called str with the value "Hello, World!".
  2. List<Character> vowels = Arrays.asList('a', 'e', 'i', 'o', 'u'); initializes a list of vowels as a List of Character objects.
  3. List<Character> characters = str.toLowerCase().chars().mapToObj(c -> (char) c).collect(Collectors.toList()); creates a new list of Character objects from the original string by using Java 8 streams to first convert the string to lowercase, then to a stream of integers representing the Unicode values of each character in the string, then to a stream of char values, and finally to a list of Character objects.
  4. long count = characters.stream().filter(c -> vowels.contains(c)).count(); counts the number of vowels in the characters list by using Java 8 streams to filter the list for characters that are vowels (i.e., contained in the vowels list), and then counting the resulting number of elements using the count() method.
  5. System.out.println("The string \"" + str + "\" contains " + count + " vowels."); prints the result by concatenating the original string str, the count of vowels count, and some explanatory text.

3.Write Program to determine if all numbers in a list are divisible by 4.


public class Example3
public static void main(String[] args)
// Initialize a list of integers 
 List<Integer> list = Arrays.asList(4, 8, 13, 16, 21); 
// Use Java 8 stream to check if all elements in the list are divisible by 4 boolean allMatch = list.stream().allMatch(e -> e % 4 == 0); 
// Print the result 
if (allMatch) { 
 System.out.println("All The Numbers Divisible By 4"); 
 } else
 System.out.println("All The Numbers Not Divisible By 4"); 
 } 
 } 
}


Explanation:

  1. List<Integer> list = Arrays.asList(4, 8, 13, 16, 21); initializes a list of integers called list with the values 4, 8, 13, 16, and 21.
  2. boolean allMatch = list.stream().allMatch(e -> e % 4 == 0); checks if all elements in the list are divisible by 4 by using Java 8 streams to create a stream of integers from the list, and then using the allMatch() method to check if all elements in the stream satisfy a given predicate. In this case, the predicate is that the element is divisible by 4 (i.e., has a remainder of 0 when divided by 4).
  3. if (allMatch) { ... } else { ... } prints the result by checking if allMatch is true or false, and printing the appropriate message. If all elements in the list are divisible by 4, then allMatch will be true, and the message "All The Numbers Divisible By 4" will be printed. Otherwise, allMatch will be false, and the message "All The Numbers Not Divisible By 4" will be printed.

4.Write a Program to group a list of strings by their values and count their occurrences.


public class Example4 { 
public static void main(String[] args)
// Initialize a list of strings 
 List<String> items = Arrays.asList("apple", "apple", "banana", "apple", "orange", "banana", "papaya"); 
// Use Java 8 stream to group the items by their values and count their occurrences // Sort the items alphabetically
 Map<String, Long> collect = items.stream() .sorted().collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); 
// Print the result System.out.println("Output " + collect); 
 } 
}


Explanation:

  1. List<String> items = Arrays.asList("apple", "apple", "banana", "apple", "orange", "banana", "papaya"); initializes a list of strings called items with the values "apple", "apple", "banana", "apple", "orange", "banana", and "papaya".
  2. Map<String, Long> collect = items.stream()... groups the items by their values and counts their occurrences by using Java 8 streams to create a stream of strings from the items, sorting the stream alphabetically using the sorted() method, and then using the groupingBy() and counting() methods of the Collectors class to group the items by their values and count their occurrences. The result is a map of string keys and long values.
  3. System.out.println("Output " + collect); prints the result by concatenating the string "Output " with the collect map and printing the resulting string. The output will be a map of string keys and long values representing the counts of each string in the items list.

5.How to find the employee with the maximum salary using Java 8 streams.


public class Employee
private String name;
private double salary; 
// Default constructor 
public Employee() {
super(); 
 } 
// Constructor with parameters 
public Employee(String name, double salary)
super(); 
this.name = name; 
this.salary = salary; 
 } 
// Getter and setter methods for the private fields 
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 class Test
public static void main(String[] args)
// Create a list of employees 
 List<Employee> emp = new ArrayList<>(); 
 emp.add(new Employee("Kartik", 10000)); 
 emp.add(new Employee("Kunal", 30000)); 
 emp.add(new Employee("Vikas", 20000)); 
 emp.add(new Employee("Yogesh", 25000)); 
 emp.add(new Employee("Pankaj", 5000)); 
// Find the employee with the maximum salary using Java 8 streams Optional<Employee> collect = emp.stream().collect(Collectors.maxBy(Comparator.comparing(Employee::getSalary))); System.out.println(collect); 
 } 
}


Explanation:

  1. The Employee class defines an Employee object with a name and salary field, as well as getter and setter methods for each field.
  2. The Test class creates a list of Employee objects and adds them to the list.
  3. Optional<Employee> collect = emp.stream().collect(Collectors.maxBy(Comparator.comparing(Employee::getSalary))); creates a stream from the emp list and uses the maxBy() method to find the employee with the maximum salary by comparing their salaries using the comparing() method. The result is an Optional<Employee> object that may or may not contain an employee with the maximum salary.
  4. System.out.println(collect); prints the result, which is the employee object with the maximum salary. If no employee has the maximum salary, the result will be an empty Optional<Employee> object.

6.Write a Program finds the common elements between two integer arrays using Java 8 Stream API.


import java.util.Arrays;
public class CommonElementsFinder {
public static void main(String[] args)
int[] arr1 = { 2, 3, 2, 8 };
int[] arr2 = { 1, 4, 3, 2 }; 
// Create a stream of arr1 and filter out elements not present in arr2 Arrays.stream(arr1) .filter(a -> Arrays.stream(arr2).anyMatch(b -> b == a)) 
// if element a is present in arr2 .distinct() // eliminate duplicates .forEach(System.out::println); // print each element on a separate line 
 } 
}


Explanation:

The Arrays.stream() method to convert the arr1 to a stream of integers. It then applies the filter() method to keep only those elements that are present in the arr2. For this, it uses the Arrays.stream() method again to convert arr2 into a stream of integers and applies the anyMatch() method to check if any element in arr2 matches the current element in arr1. If the anyMatch() method returns true, it means the element is present in arr2, and it will be passed through the filter.

The distinct() method is then applied to eliminate any duplicates from the resulting stream. Finally, the forEach() method is used to print each element on a separate line. The output of this program will be the common elements between arr1 and arr2.

7.Write a Program to find starts and with same character.


public class Example7 { 
public static void main(String[] args)
 List<String> list = Arrays.asList("kartik", "Ram", "madam"); 
// Use Java 8 stream to filter the list based on the conditions and print the results 
 list.stream() .filter(e -> e.length() > 0 && e.endsWith(String.valueOf(e.charAt(0)))) .forEach(System.out::println); 
 } 
}


Explanation:

  1. The code creates a List of String containing some words.
  2. The Java 8 stream API is used to filter the list based on the following conditions: The length of the string should be greater than 0 (e.length() > 0).
  3. The string should end with the same character as the first character of the string (e.endsWith(String.valueOf(e.charAt(0)))).
  4. The forEach method is used to print the filtered elements. The System.out::println is a method reference which is used to print each element in a new line.

8.Write a Java 8 Program to Print ten random numbers using forEach.


import java.util.Random; 
public class RandomNumbers
public static void main(String[] args)
Random random = new Random(); 
 random.ints(10, 0, 100) .forEach(System.out::println); 
 } 
}


Explanation:

  1. We first create a Random object to generate random numbers.
  2. We then use the ints method to generate 10 random integers between 0 (inclusive) and 100 (exclusive).
  3. Finally, we use the forEach method to print each of these random integers using a method reference (System.out::println).

9.Write a Java 8 program to Count Strings whose length is greater than 3 in List.


import java.util.Arrays; 
import java.util.List; 
public class StringLengthCounter
public static void main(String[] args)
 List<String> words = Arrays.asList("hello", "world", "java", "eight", "program"); 
long count = words.stream() .filter(word -> word.length() > 3) .count(); 
 System.out.println("Number of strings with length greater than 3: " + count); 
 } 
}


Explanation:

  1. We first create a list of strings using the Arrays.asList method.
  2. We then use the stream method to convert the list to a stream of elements.
  3. We use the filter method to keep only the elements whose length is greater than 3.
  4. We use the count method to count the number of elements in the stream.
  5. Finally, we print the count using System.out.println.

10.How to check if list is empty in Java 8 using Optional, if not null iterate through the list and print the object?


import java.util.ArrayList; 
import java.util.List; 
import java.util.Optional; 
public class ListPrinter
public static void main(String[] args) {
 List<String> list = new ArrayList<>(); list.add("apple"); list.add("banana"); list.add("cherry"); 
 Optional<List<String>> optionalList = Optional.ofNullable(list); 
if (optionalList.isPresent() && !optionalList.get().isEmpty()) { optionalList.get().forEach(System.out::println); 
 } 
 }
 }


Explanation:

  1. We first create a list of strings and add some elements to it.
  2. We then create an Optional object using the ofNullable method, which can hold either a non-null object or be empty.
  3. We check if the optionalList object is present (i.e., not empty) and the list inside it is also not empty using the isPresent and isEmpty methods respectively.
  4. If both the conditions are true, we use the forEach method to iterate through the list and print each element using a method reference (System.out::println).

Conclusion

Java8 coding interview can be a challenging but rewarding experience that allows candidates to showcase their knowledge of the latest Java features and their practical applications. To succeed in a Java8 coding interview, candidates should have a strong understanding of streams, lambdas, and functional interfaces, as well as the ability to think critically, communicate effectively, and adapt to new situations. With the right preparation and approach, candidates can demonstrate their proficiency with Java8 and stand out as strong candidates for the position.

No comments:

Post a Comment