[Go to site: main page, start]

0% found this document useful (0 votes)
90 views2 pages

Java 8 Interview Coding Questions

Uploaded by

ramjai6543
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
90 views2 pages

Java 8 Interview Coding Questions

Uploaded by

ramjai6543
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java 8 Coding Questions & Answers

Below are practical Java 8 coding questions with answers and code snippets to demonstrate real-
world use of Streams, Lambdas, Optional, Date/Time, and more.
1. Convert a List of Strings to Uppercase using Streams
Explanation: Use map() to transform each element and collect the result into a new list.
Code:
List<String> names = [Link]("alice", "bob", "charlie");
List<String> upper = [Link]()
.map(String::toUpperCase)
.collect([Link]());
[Link](upper);

2. Find the Second Highest Number in a List


Explanation: Sort in descending order, skip the first element, then find the first of the
remaining elements.
Code:
List<Integer> nums = [Link](5, 3, 9, 1, 9, 7);
int secondHighest = [Link]()
.distinct()
.sorted([Link]())
.skip(1)
.findFirst()
.orElseThrow();
[Link](secondHighest);

3. Count Occurrences of Each Character in a String


Explanation: Use chars() to create an IntStream, then collect using groupingBy.
Code:
String input = "banana";
Map<Character, Long> freq = [Link]()
.mapToObj(c -> (char) c)
.collect([Link](c -> c, [Link]()));
[Link](freq);

4. Sum of All Even Numbers in a List


Explanation: Filter even numbers and sum using mapToInt.
Code:
List<Integer> nums = [Link](2, 5, 8, 11, 14);
int sum = [Link]()
.filter(n -> n % 2 == 0)
.mapToInt(Integer::intValue)
.sum();
[Link](sum);

5. Get the Current Date and Time in a Specific Format


Explanation: Use [Link] and DateTimeFormatter.
Code:
LocalDateTime now = [Link]();
String formatted = [Link]([Link]("dd-MM-yyyy HH:mm:ss"));
[Link](formatted);
6. Find Duplicate Elements in a List
Explanation: Use a Set to track seen elements and filter duplicates.
Code:
List<Integer> nums = [Link](1, 2, 3, 2, 4, 3, 5);
Set<Integer> seen = new HashSet<>();
Set<Integer> duplicates = [Link]()
.filter(n -> ![Link](n))
.collect([Link]());
[Link](duplicates);

7. Use Optional to Avoid Null Checks


Explanation: Wrap a nullable value with Optional and provide a default.
Code:
String value = null;
String result = [Link](value)
.orElse("Default Value");
[Link](result);

8. Group Employees by Department


Explanation: Use groupingBy collector to group objects by a key.
Code:
class Employee { String name; String dept; /* constructor/getters */ }
List<Employee> employees = [Link](
new Employee("Alice","HR"), new Employee("Bob","IT"), new Employee("Charlie","HR"));
Map<String, List<Employee>> byDept = [Link]()
.collect([Link](Employee::getDept));
[Link](byDept);

9. Parallel Stream Example


Explanation: Use parallelStream to perform computations concurrently.
Code:
List<Integer> nums = [Link](1, 10).boxed().collect([Link]());
int sum = [Link]().mapToInt(Integer::intValue).sum();
[Link](sum);

10. Find the Longest String in a List


Explanation: Use max() with a Comparator comparing length.
Code:
List<String> words = [Link]("apple", "banana", "pear", "strawberry");
String longest = [Link]()
.max([Link](String::length))
.orElse("");
[Link](longest);

End of Java 8 Coding Questions

Common questions

Powered by AI

In Java 8, use Optional.ofNullable() to wrap a potentially null value. The orElse method can be used to provide a default value if the wrapped value is null. For example: String value = null; String result = Optional.ofNullable(value).orElse("Default Value")

To count character frequency in a string using Java 8, utilize the chars() method to create an IntStream, then convert the stream of int to a stream of characters using mapToObj. Finally, use Collectors.groupingBy() with Collectors.counting() to count occurrences of each character. Example: String input = "banana"; Map<Character, Long> freq = input.chars().mapToObj(c -> (char) c).collect(Collectors.groupingBy(c -> c, Collectors.counting()))

To find the second highest number in a list using Java 8 streams, first use distinct() to remove duplicates, then sort the list in descending order using Comparator.reverseOrder(). After sorting, use skip(1) to bypass the highest element and findFirst() to get the next element, which represents the second highest number. Example: List<Integer> nums = Arrays.asList(5, 3, 9, 1, 9, 7); int secondHighest = nums.stream().distinct().sorted(Comparator.reverseOrder()).skip(1).findFirst().orElseThrow()

In Java 8, use LocalDateTime.now() to obtain the current date and time, and apply the format() method with a DateTimeFormatter. Specify the desired pattern using DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss") for formatting. Example: LocalDateTime now = LocalDateTime.now(); String formatted = now.format(DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss"))

In Java 8, you can transform a list of strings to uppercase by using the map() function in Streams to apply the String::toUpperCase method to each element. Then, you collect the results into a new list using Collectors.toList(). Example: List<String> names = Arrays.asList("alice", "bob", "charlie"); List<String> upper = names.stream().map(String::toUpperCase).collect(Collectors.toList())

To sum all even numbers in a list using Java 8, filter the stream with n -> n % 2 == 0 to only include even numbers. Use mapToInt to convert to an IntStream, and then sum() to compute the total. Example: List<Integer> nums = Arrays.asList(2, 5, 8, 11, 14); int sum = nums.stream().filter(n -> n % 2 == 0).mapToInt(Integer::intValue).sum()

To find duplicate elements in a list using Java 8, maintain a Set to track seen elements. As you process the stream, filter using the condition !seen.add(n) to collect only duplicates. Use Collectors.toSet() to gather these duplicates. Example: List<Integer> nums = Arrays.asList(1, 2, 3, 2, 4, 3, 5); Set<Integer> duplicates = nums.stream().filter(n -> !seen.add(n)).collect(Collectors.toSet())

To find the longest string in a list using Java 8 Stream, utilize the max() method with a Comparator that compares String lengths. This method finds the maximum element based on the provided comparator. Example: List<String> words = Arrays.asList("apple", "banana", "pear", "strawberry"); String longest = words.stream().max(Comparator.comparingInt(String::length)).orElse("")

Parallel streams in Java 8 allow concurrent computations by dividing the tasks among multiple threads, increasing performance for large datasets. Using parallelStream() on a collection enables this behavior. For example, computing the sum of numbers in a list: List<Integer> nums = IntStream.rangeClosed(1, 10).boxed().collect(Collectors.toList()); int sum = nums.parallelStream().mapToInt(Integer::intValue).sum(); leverages parallelism for potential efficiency gains.

Using Java 8 streams, group a list of Employee objects by their department with Collectors.groupingBy(). This method takes a classifier function, such as Employee::getDept, to organize employees into maps based on department. Example: Map<String, List<Employee>> byDept = employees.stream().collect(Collectors.groupingBy(Employee::getDept))

You might also like