Friday, June 28, 2024

50 Java 8 Interview Programs with Solutions

This blog post presents 50 Java 8 interview programs along with their solutions. These examples demonstrate various features and concepts introduced in Java 8, particularly focusing on streams, lambdas, and functional programming.

1. Find the sum of all numbers in a list using streams

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

public class SumOfNumbers {
    public static void main(String[] args) {
        List numbers = Arrays.asList(1, 2, 3, 4, 5);
        int sum = numbers.stream().mapToInt(Integer::intValue).sum();
        System.out.println("Sum: " + sum);
    }
}
    

2. Find the average of numbers in a list using streams

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

public class AverageOfNumbers {
    public static void main(String[] args) {
        List numbers = Arrays.asList(1, 2, 3, 4, 5);
        double average = numbers.stream().mapToInt(Integer::intValue).average().orElse(0.0);
        System.out.println("Average: " + average);
    }
}
    

3. Count the number of strings in a list with length greater than 3

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

public class CountStrings {
    public static void main(String[] args) {
        List strings = Arrays.asList("a", "ab", "abc", "abcd", "abcde");
        long count = strings.stream().filter(s -> s.length() > 3).count();
        System.out.println("Count: " + count);
    }
}
    

4. Remove all empty strings from a list

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

public class RemoveEmptyStrings {
    public static void main(String[] args) {
        List strings = Arrays.asList("abc", "", "bc", "efg", "abcd", "", "jkl");
        List filtered = strings.stream().filter(s -> !s.isEmpty()).collect(Collectors.toList());
        System.out.println("Filtered List: " + filtered);
    }
}
    

5. Convert a list of strings to uppercase

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

public class UppercaseStrings {
    public static void main(String[] args) {
        List strings = Arrays.asList("a", "b", "c", "d", "e");
        List uppercase = strings.stream().map(String::toUpperCase).collect(Collectors.toList());
        System.out.println("Uppercase: " + uppercase);
    }
}
    

6. Find the maximum value in a list of integers

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

public class MaxValue {
    public static void main(String[] args) {
        List numbers = Arrays.asList(1, 5, 3, 8, 2);
        int max = numbers.stream().max(Integer::compare).orElse(0);
        System.out.println("Max value: " + max);
    }
}
    

7. Sort a list of strings in alphabetical order

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

public class SortStrings {
    public static void main(String[] args) {
        List strings = Arrays.asList("d", "b", "a", "c", "e");
        List sorted = strings.stream().sorted().collect(Collectors.toList());
        System.out.println("Sorted: " + sorted);
    }
}
    

8. Find the first non-repeated character in a string

import java.util.LinkedHashMap;
import java.util.function.Function;
import java.util.stream.Collectors;

public class FirstNonRepeatedChar {
    public static void main(String[] args) {
        String input = "aabbcdeeff";
        Character result = input.chars()
                .mapToObj(ch -> Character.toLowerCase((char) ch))
                .collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting()))
                .entrySet()
                .stream()
                .filter(entry -> entry.getValue() == 1L)
                .map(entry -> entry.getKey())
                .findFirst()
                .orElse(null);
        System.out.println("First non-repeated character: " + result);
    }
}
    

9. Check if a number is prime

import java.util.stream.IntStream;

public class PrimeNumber {
    public static void main(String[] args) {
        int number = 17;
        boolean isPrime = number > 1 && IntStream.rangeClosed(2, (int) Math.sqrt(number)).noneMatch(i -> number % i == 0);
        System.out.println(number + " is prime: " + isPrime);
    }
}
    

10. Generate Fibonacci series up to n terms

import java.util.stream.Stream;

public class FibonacciSeries {
    public static void main(String[] args) {
        int n = 10;
        Stream.iterate(new int[]{0, 1}, f -> new int[]{f[1], f[0] + f[1]})
              .limit(n)
              .map(f -> f[0])
              .forEach(i -> System.out.print(i + " "));
    }
}
    

11. Find all pairs of elements in an array whose sum is equal to a given number

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

public class PairSum {
    public static void main(String[] args) {
        int[] numbers = {2, 4, 3, 5, 7, 8, 9};
        int targetSum = 7;
        
        List pairs = Arrays.stream(numbers)
            .boxed()
            .flatMap(i -> Arrays.stream(numbers)
                .filter(j -> i + j == targetSum && i <= j)
                .mapToObj(j -> i + "," + j))
            .collect(Collectors.toList());
        
        System.out.println("Pairs with sum " + targetSum + ": " + pairs);
    }
}
    

12. Check if a string is a palindrome

import java.util.stream.IntStream;

public class Palindrome {
    public static void main(String[] args) {
        String str = "racecar";
        boolean isPalindrome = IntStream.range(0, str.length() / 2)
            .allMatch(i -> str.charAt(i) == str.charAt(str.length() - 1 - i));
        
        System.out.println(str + " is palindrome: " + isPalindrome);
    }
}
    

13. Find the factorial of a number using streams

import java.util.stream.LongStream;

public class Factorial {
    public static void main(String[] args) {
        int n = 5;
        long factorial = LongStream.rangeClosed(1, n)
            .reduce(1, (long x, long y) -> x * y);
        
        System.out.println("Factorial of " + n + " is: " + factorial);
    }
}
    

14. Find the second largest number in an array

import java.util.Arrays;

public class SecondLargest {
    public static void main(String[] args) {
        int[] numbers = {5, 9, 11, 2, 8, 21, 1};
        
        int secondLargest = Arrays.stream(numbers)
            .boxed()
            .sorted((a, b) -> b.compareTo(a))
            .skip(1)
            .findFirst()
            .orElse(-1);
        
        System.out.println("Second largest number: " + secondLargest);
    }
}
    

15. Remove duplicates from a list

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

public class RemoveDuplicates {
    public static void main(String[] args) {
        List numbers = Arrays.asList(1, 2, 3, 2, 4, 3, 5);
        
        List distinctNumbers = numbers.stream()
            .distinct()
            .collect(Collectors.toList());
        
        System.out.println("List without duplicates: " + distinctNumbers);
    }
}
    

16. Find the longest string in a list

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

public class LongestString {
    public static void main(String[] args) {
        List strings = Arrays.asList("Java", "Python", "JavaScript", "C++", "Ruby");
        
        String longest = strings.stream()
            .reduce((s1, s2) -> s1.length() > s2.length() ? s1 : s2)
            .orElse("");
        
        System.out.println("Longest string: " + longest);
    }
}
    

17. Count occurrences of each character in a string

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

public class CharacterCount {
    public static void main(String[] args) {
        String str = "programming";
        
        Map charCount = str.chars()
            .mapToObj(ch -> (char) ch)
            .collect(Collectors.groupingBy(ch -> ch, Collectors.counting()));
        
        System.out.println("Character count: " + charCount);
    }
}
    

18. Join a list of strings with a delimiter

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

public class JoinStrings {
    public static void main(String[] args) {
        List fruits = Arrays.asList("apple", "banana", "cherry", "date");
        
        String joined = fruits.stream()
            .collect(Collectors.joining(", "));
        
        System.out.println("Joined string: " + joined);
    }
}
    

19. Check if all elements in a list are even

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

public class AllEven {
    public static void main(String[] args) {
        List numbers = Arrays.asList(2, 4, 6, 8, 10);
        
        boolean allEven = numbers.stream()
            .allMatch(n -> n % 2 == 0);
        
        System.out.println("All numbers are even: " + allEven);
    }
}
    

20. Find the sum of squares of all odd numbers in a list

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

public class SumOfSquaresOfOdd {
    public static void main(String[] args) {
        List numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
        
        int sumOfSquaresOfOdd = numbers.stream()
            .filter(n -> n % 2 != 0)
            .mapToInt(n -> n * n)
            .sum();
        
        System.out.println("Sum of squares of odd numbers: " + sumOfSquaresOfOdd);
    }
}
    

21. Convert a list of integers to an array

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

public class ListToArray {
    public static void main(String[] args) {
        List numbers = Arrays.asList(1, 2, 3, 4, 5);
        
        int[] array = numbers.stream()
            .mapToInt(Integer::intValue)
            .toArray();
        
        System.out.println("Array: " + Arrays.toString(array));
    }
}
    

22. Find the most frequent element in an array

import java.util.Arrays;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class MostFrequentElement {
    public static void main(String[] args) {
        Integer[] numbers = {1, 2, 3, 2, 4, 2, 5, 3};
        
        Map.Entry mostFrequent = Arrays.stream(numbers)
            .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
            .entrySet()
            .stream()
            .max(Map.Entry.comparingByValue())
            .orElse(null);
        
        System.out.println("Most frequent element: " + (mostFrequent != null ? mostFrequent.getKey() : "None"));
    }
}
    

23. Check if a string contains only digits

public class OnlyDigits {
    public static void main(String[] args) {
        String str = "12345";
        
        boolean onlyDigits = str.chars()
            .allMatch(Character::isDigit);
        
        System.out.println("String contains only digits: " + onlyDigits);
    }
}
    

24. Find the sum of all even numbers in a range

import java.util.stream.IntStream;

public class SumOfEvenInRange {
    public static void main(String[] args) {
        int start = 1;
        int end = 100;
        
        int sum = IntStream.rangeClosed(start, end)
            .filter(n -> n % 2 == 0)
            .sum();
        
        System.out.println("Sum of even numbers from " + start + " to " + end + ": " + sum);
    }
}
    

25. Reverse the order of words in a sentence

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

public class ReverseSentence {
    public static void main(String[] args) {
        String sentence = "Hello World Java Programming";
        
        List words = Arrays.asList(sentence.split("\\s+"));
        Collections.reverse(words);
        
        String reversed = words.stream()
            .collect(Collectors.joining(" "));
        
        System.out.println("Reversed sentence: " + reversed);
    }
}
    

26. Find the intersection of two lists

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

public class ListIntersection {
    public static void main(String[] args) {
        List list1 = Arrays.asList(1, 2, 3, 4, 5);
        List list2 = Arrays.asList(4, 5, 6, 7, 8);
        
        List intersection = list1.stream()
            .filter(list2::contains)
            .collect(Collectors.toList());
        
        System.out.println("Intersection: " + intersection);
    }
}
    

27. Calculate the product of all numbers in a list

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

public class ProductOfList {
    public static void main(String[] args) {
        List numbers = Arrays.asList(1, 2, 3, 4, 5);
        
        int product = numbers.stream()
            .reduce(1, (a, b) -> a * b);
        
        System.out.println("Product: " + product);
    }
}
    

28. Find all strings that start with a specific letter

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

public class StringsStartingWith {
    public static void main(String[] args) {
        List words = Arrays.asList("apple", "banana", "avocado", "cherry", "apricot");
        char startLetter = 'a';
        
        List filteredWords = words.stream()
            .filter(w -> w.toLowerCase().startsWith(String.valueOf(startLetter).toLowerCase()))
            .collect(Collectors.toList());
        
        System.out.println("Words starting with '" + startLetter + "': " + filteredWords);
    }
}
    

29. Calculate the average length of strings in a list

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

public class AverageStringLength {
    public static void main(String[] args) {
        List words = Arrays.asList("Java", "Python", "C++", "JavaScript", "Ruby");
        
        double averageLength = words.stream()
            .mapToInt(String::length)
            .average()
            .orElse(0.0);
        
        System.out.println("Average length: " + averageLength);
    }
}
    

30. Find the smallest number in a list that is greater than a given number

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

public class SmallestGreaterThan {
    public static void main(String[] args) {
        List numbers = Arrays.asList(1, 3, 5, 7, 9, 11, 13);
        int target = 6;
        
        int result = numbers.stream()
            .filter(n -> n > target)
            .min(Integer::compare)
            .orElse(-1);
        
        System.out.println("Smallest number greater than " + target + ": " + result);
    }
}
    

31. Group a list of objects by a property

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

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

public class GroupByAge {
    public static void main(String[] args) {
        List people = Arrays.asList(
            new Person("Alice", 25),
            new Person("Bob", 30),
            new Person("Charlie", 25),
            new Person("David", 30)
        );
        
        Map> groupedByAge = people.stream()
            .collect(Collectors.groupingBy(p -> p.age));
        
        System.out.println("Grouped by age: " + groupedByAge);
    }
}
    

32. Find the length of the longest word in a sentence

public class LongestWordLength {
    public static void main(String[] args) {
        String sentence = "The quick brown fox jumps over the lazy dog";
        
        int maxLength = sentence.split("\\s+").length > 0 ?
            sentence.split("\\s+")
                .stream()
                .mapToInt(String::length)
                .max()
                .orElse(0) : 0;
        
        System.out.println("Length of longest word: " + maxLength);
    }
}
    

33. Check if a list contains any element starting with a specific prefix

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

public class ContainsPrefix {
    public static void main(String[] args) {
        List words = Arrays.asList("apple", "banana", "cherry", "date");
        String prefix = "ba";
        
        boolean containsPrefix = words.stream()
            .anyMatch(w -> w.startsWith(prefix));
        
        System.out.println("Contains word with prefix '" + prefix + "': " + containsPrefix);
    }
}
    

34. Convert a list of strings to lowercase

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

public class ToLowerCase {
    public static void main(String[] args) {
        List words = Arrays.asList("HELLO", "World", "JAVA", "Programming");
        
        List lowercaseWords = words.stream()
            .map(String::toLowerCase)
            .collect(Collectors.toList());
        
        System.out.println("Lowercase words: " + lowercaseWords);
    }
}
    

35. Find the sum of digits of a number

public class SumOfDigits {
    public static void main(String[] args) {
        int number = 12345;
        
        int sum = String.valueOf(number)
            .chars()
            .map(Character::getNumericValue)
            .sum();
        
        System.out.println("Sum of digits: " + sum);
    }
}
    

36. Check if a list is sorted

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

public class IsSorted {
    public static void main(String[] args) {
        List numbers = Arrays.asList(1, 2, 3, 4, 5);
        
        boolean isSorted = numbers.stream()
            .sorted()
            .collect(Collectors.toList())
            .equals(numbers);
        
        System.out.println("Is list sorted: " + isSorted);
    }
}
    

37. Find the kth largest element in an array

import java.util.Arrays;

public class KthLargest {
    public static void main(String[] args) {
        int[] numbers = {3, 2, 1, 5, 6, 4};
        int k = 2;
        
        int kthLargest = Arrays.stream(numbers)
            .boxed()
            .sorted((a, b) -> b.compareTo(a))
            .skip(k - 1)
            .findFirst()
            .orElse(-1);
        
        System.out.println(k + "th largest element: " + kthLargest);
    }
}
    

38. Remove all vowels from a string

public class RemoveVowels {
    public static void main(String[] args) {
        String str = "Hello World";
        
        String result = str.replaceAll("[aeiouAEIOU]", "");
        
        System.out.println("String without vowels: " + result);
    }
}
    

39. Find the common elements between two arrays

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

public class CommonElements {
    public static void main(String[] args) {
        Integer[] arr1 = {1, 2, 3, 4, 5};
        Integer[] arr2 = {4, 5, 6, 7, 8};
        
        List common = Arrays.stream(arr1)
            .filter(Arrays.asList(arr2)::contains)
            .collect(Collectors.toList());
        
        System.out.println("Common elements: " + common);
    }
}
    

40. Calculate the factorial of a number using reduce

import java.util.stream.LongStream;

public class FactorialUsingReduce {
    public static void main(String[] args) {
        int n = 5;
        
        long factorial = LongStream.rangeClosed(1, n)
            .reduce(1, (long x, long y) -> x * y);
        
        System.out.println("Factorial of " + n + ": " + factorial);
    }
}
    

41. Find the longest palindrome in a string

import java.util.stream.IntStream;

public class LongestPalindrome {
    public static void main(String[] args) {
        String str = "babad";
        
        String longest = IntStream.range(0, str.length())
            .boxed()
            .flatMap(i -> IntStream.rangeClosed(i + 1, str.length())
                .mapToObj(j -> str.substring(i, j)))
            .filter(s -> s.equals(new StringBuilder(s).reverse().toString()))
            .max((s1, s2) -> s1.length() - s2.length())
            .orElse("");
        
        System.out.println("Longest palindrome: " + longest);
    }
}
    

42. Convert a list of integers to a comma-separated string

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

public class ListToString {
    public static void main(String[] args) {
        List numbers = Arrays.asList(1, 2, 3, 4, 5);
        
        String result = numbers.stream()
            .map(String::valueOf)
            .collect(Collectors.joining(", "));
        
        System.out.println("Comma-separated string: " + result);
    }
}
    

43. Find the sum of squares of even numbers in a list

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

public class SumOfSquaresOfEven {
    public static void main(String[] args) {
        List numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
        
        int sum = numbers.stream()
            .filter(n -> n % 2 == 0)
            .mapToInt(n -> n * n)
            .sum();
        
        System.out.println("Sum of squares of even numbers: " + sum);
    }
}
    

44. Check if a number is a perfect square

import java.util.stream.IntStream;

public class PerfectSquare {
    public static void main(String[] args) {
        int number = 16;
        
        boolean isPerfectSquare = IntStream.rangeClosed(1, (int) Math.sqrt(number))
            .anyMatch(i -> i * i == number);
        
        System.out.println(number + " is a perfect square: " + isPerfectSquare);
    }
}
    

45. Find the first repeating element in an array

import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class FirstRepeatingElement {
    public static void main(String[] args) {
        Integer[] numbers = {1, 2, 3, 4, 2, 1, 5, 6};
        
        Integer firstRepeating = Arrays.stream(numbers)
            .collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting()))
            .entrySet()
            .stream()
            .filter(entry -> entry.getValue() > 1)
            .map(Map.Entry::getKey)
            .findFirst()
            .orElse(null);
        
        System.out.println("First repeating element: " + firstRepeating);
    }
}
    

46. Calculate the product of all odd numbers in a list

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

public class ProductOfOdd {
    public static void main(String[] args) {
        List numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
        
        int product = numbers.stream()
            .filter(n -> n % 2 != 0)
            .reduce(1, (a, b) -> a * b);
        
        System.out.println("Product of odd numbers: " + product);
    }
}
    

47. Find the difference between the largest and smallest numbers in a list

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

public class LargestSmallestDifference {
    public static void main(String[] args) {
        List numbers = Arrays.asList(5, 2, 8, 1, 9, 3);
        
        int difference = numbers.stream()
            .reduce((a, b) -> Math.max(a, b) - Math.min(a, b))
            .orElse(0);
        
        System.out.println("Difference between largest and smallest: " + difference);
    }
}
    

48. Check if a string contains only unique characters

public class UniqueCharacters {
    public static void main(String[] args) {
        String str = "abcdefg";
        
        boolean hasUniqueChars = str.chars()
            .distinct()
            .count() == str.length();
        
        System.out.println("String has only unique characters: " + hasUniqueChars);
    }
}
    

49. Find the sum of all numbers in a string

public class SumOfNumbersInString {
    public static void main(String[] args) {
        String str = "ab12c3d4ef5";
        
        int sum = str.replaceAll("\\D+", " ")
            .trim()
            .split(" ")
            .length > 0 ?
            str.replaceAll("\\D+", " ")
                .trim()
                .split(" ")
                .stream()
                .mapToInt(Integer::parseInt)
                .sum() : 0;
        
        System.out.println("Sum of numbers in string: " + sum);
    }
}
    

50. Implement a custom Collector to join strings with a delimiter

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

public class CustomCollector {
    public static void main(String[] args) {
        List fruits = Arrays.asList("apple", "banana", "cherry", "date");
        
        String result = fruits.stream()
            .collect(Collector.of(
                StringBuilder::new,
                (sb, str) -> {
                    if (sb.length() > 0) sb.append(", ");
                    sb.append(str);
                },
                StringBuilder::append,
                StringBuilder::toString
            ));
        
        System.out.println("Joined string: " + result);
    }
}
    
These 50 Java 8 interview programs cover a wide range of concepts and techniques. Practice these examples to improve your understanding of Java 8 features and prepare for Java interviews.

If you need any further assistance, such as explanations of specific programs, modifications to the code, or help with implementing these examples, please don't hesitate to ask. Good luck with your Java programming endeavors!

0 comments:

Post a Comment

Contact

Get in touch with me


Adress/Street

Bangalore, India