Java 8 Interview Coding Questions
Java 8 Interview Coding Questions
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))