Java interview questions on streams

Java interview questions on streams

Core Concepts

  1. What is a Stream?
    A sequence of elements that supports sequential or parallel operations. Streams do not store data; they operate on a source (e.g., collection) and support functional-style operations such as filter, map, and reduce.

  2. Stream vs. Collection

    • Collections store data, while streams process it on demand.
    • Streams are lazy, meaning operations execute only when a terminal operation is invoked.
  3. Intermediate vs. Terminal Operations

    • Intermediate operations: filter, map, sorted (return a new stream, lazy).
    • Terminal operations: collect, forEach, reduce (produce a result or side effect, eager).

Common Operations

  1. Filter vs. Map

    • filter(Predicate): Selects elements matching a condition.
    • map(Function): Transforms elements into another shape, such as extracting a field.
  2. Reduce
    Combines elements into a single result, such as the sum of numbers:

    int sum = numbers.stream().reduce(0, (a, b) -> a + b);
    
  3. FlatMap
    Flattens nested collections (e.g., List<List> to List):

    List<Integer> flatList = nestedList.stream().flatMap(List::stream).toList();
    

Advanced Concepts

  1. Parallel Streams

    • Allow processing to occur in multiple threads using parallelStream().
    • Thread safety: Ensure the lambda expression is stateless or non-interfering.
  2. Stateful vs. Stateless Operations

    • Stateless: filter, map (do not depend on other elements).
    • Stateful: distinct, sorted (must keep everything in memory).
  3. Short-Circuiting Operations
    These operations end processing early, such as findFirst, limit, and anyMatch.

Collectors

  1. Collectors.toList
    Collects the values of a stream into a list:

    List<String> names = people.stream().map(Person::getName).toList();
    
  2. GroupingBy
    Groups elements by a classifier, such as grouping people by age:

    Map<Integer, List<Person>> peopleByAge = people.stream()
        .collect(Collectors.groupingBy(Person::getAge));
    
  3. PartitioningBy
    Splits elements into two groups (true/false) based on a predicate:

    Map<Boolean, List<Person>> partitioned = people.stream()
        .collect(Collectors.partitioningBy(p -> p.getAge() >= 18));
    

Coding Problems

  1. Find distinct elements in a list:

    List<Integer> distinct = numbers.stream().distinct().toList();
    
  2. Sum all even numbers:

    int sum = numbers.stream().filter(n -> n % 2 == 0).mapToInt(n -> n).sum();
    
  3. Convert a list of strings to uppercase:

    List<String> upper = strings.stream().map(String::toUpperCase).toList();
    
  4. Find the longest string in a list:

    Optional<String> longest = strings.stream()
        .max(Comparator.comparingInt(String::length));
    
  5. Concatenate two streams:

    Stream<String> combined = Stream.concat(stream1, stream2);
    

Best Practices & Pitfalls

  1. Avoid Side Effects
    Stream operations should be stateless; avoid modifying external variables in lambdas.

  2. Primitive Streams
    Performance can be improved using IntStream, LongStream, or DoubleStream for primitive types.

  3. Reusing Streams
    Streams are one-time use only; create new ones if needed.

  4. ForEach vs. For-Loops
    Prefer forEach for clarity, but avoid it for complex mutations or state modifications.

Scenario-Based Interview programming Questions On Java Streams

  1. How to handle exceptions in streams?
    Wrap checked exceptions in a lambda with try-catch or use utility methods like Unchecked:

    List<String> result = files.stream().map(file -> { 
        try { 
            return readFile(file); 
        } catch (IOException e) { 
            throw new UncheckedIOException(e); 
        } 
    }).toList();
    
  2. When to use parallel streams?
    Use for large volumes of data and CPU-bound tasks but avoid for I/O operations or small datasets.

  3. Why does peek exist?
    Used for debugging/logging intermediate stream states, such as peek(System.out::println).

Advanced Coding Challenges

  1. Find the second-largest number in a list:

    OptionalInt secondLargest = numbers.stream()
        .distinct()
        .sorted()
        .skip(numbers.size() - 2)
        .findFirst();
    
  2. Merge two lists of objects into a map (ID → Object):

    Map<Integer, Person> idToPerson = people.stream()
        .collect(Collectors.toMap(Person::getId, Function.identity()));
    
  3. Count occurrences of every word in a list:

    Map<String, Long> wordCount = words.stream()
        .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
    

These questions cover fundamental programming concepts, best practices, and optimization strategies. Senior developers may also focus on parallel stream effectiveness and custom collectors.

Java 8 coding interview questions

 Java 8 coding questions:

Problem Solution
Separate Odd and Even Numbers listOfIntegers.stream().collect(Collectors.partitioningBy(number -> number % 2 == 0));
Remove Duplicates from List listOfStrings.stream().distinct().toList();
Character Frequency in String input.chars().mapToObj(c -> (char) c).collect(Collectors.groupingBy(ch -> ch, Collectors.counting()));
Frequency of Array Elements list.stream().collect(Collectors.groupingBy(element -> element, Collectors.counting()));
Sort List in Reverse list.sort(Comparator.reverseOrder()); list.forEach(System.out::println);
Join Strings with Prefix/Suffix list.stream().collect(Collectors.joining("-", "Start-", "-End"));
Filter Multiples of 5 list.stream().filter(number -> number % 5 == 0).forEach(System.out::println);
Merge Arrays and Sort IntStream.concat(Arrays.stream(arr1), Arrays.stream(arr2)).sorted().toArray();
Merge and Remove Duplicates IntStream.concat(Arrays.stream(arr1), Arrays.stream(arr2)).distinct().sorted().toArray();
Find Top 3 Minimum Values list.stream().sorted().limit(3).toList();
Find Top 3 Maximum Values list.stream().sorted(Comparator.reverseOrder()).limit(3).toList();
Sort Strings by Length list.stream().sorted(Comparator.comparing(String::length)).forEach(System.out::println);
Sum and Average of Array int sum = Arrays.stream(inputArray).sum(); double average = Arrays.stream(inputArray).average().orElse(0);
Reverse Integer Array IntStream.range(0, arr.length).map(i -> arr[arr.length - 1 - i]).toArray();
Check Palindrome boolean isPalindrome = IntStream.range(0, str.length() / 2).noneMatch(i -> str.charAt(i) != str.charAt(str.length() - i - 1));
Find Second Largest Number list.stream().sorted(Comparator.reverseOrder()).skip(1).findFirst().orElseThrow();
Common Elements Between Arrays list1.stream().filter(list2::contains).toList();
Reverse Words in String Arrays.stream(str.split(" ")).map(word -> new StringBuilder(word).reverse().toString()).collect(Collectors.joining(" "));
Find Strings Starting with Numbers list.stream().filter(s -> Character.isDigit(s.charAt(0))).toList();
Sum of Digits in Number String.valueOf(input).chars().map(Character::getNumericValue).sum();
Last Element of List list.get(list.size() - 1);
Age from Birth Year Period.between(LocalDate.of(1985, 1, 23), LocalDate.now()).getYears();
Fibonacci Series Stream.iterate(new int[]{0, 1}, fib -> new int[]{fib[1], fib[0] + fib[1]}).limit(10).map(fib -> fib[0]).toList();

This table properly structures the Java 8 coding problems with their corresponding solutions. Let me know if you need any modifications! 

Java 8 Coding Interview Questions and Answers

This document contains a collection of Java 8 coding interview questions along with their answers. These questions focus on key Java 8 features such as Streams, Lambda Expressions, Functional Interfaces, and Method References.

1. Filtering a List and Summing Even Numbers using Streams

Question: Given a list of integers, write a Java 8 program to filter out even numbers and calculate their sum.

Answer:

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

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

        int sum = numbers.stream()
                         .filter(n -> n % 2 == 0) // Filter even numbers
                         .mapToInt(Integer::intValue) // Convert to IntStream
                         .sum(); // Calculate sum

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

Output:

Sum of even numbers: 30

2. Sorting a List of Strings in Ascending and Descending Order

Question: Write a Java 8 program to sort a list of strings in both ascending and descending order.

Answer:

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

public class SortStrings {
    public static void main(String[] args) {
        List<String> names = Arrays.asList("John", "Alice", "Bob", "Charlie");

        // Ascending order
        List<String> ascendingOrder = names.stream()
                                           .sorted()
                                           .collect(Collectors.toList());

        // Descending order
        List<String> descendingOrder = names.stream()
                                            .sorted((s1, s2) -> s2.compareTo(s1))
                                            .collect(Collectors.toList());

        System.out.println("Ascending Order: " + ascendingOrder);
        System.out.println("Descending Order: " + descendingOrder);
    }
}

Output:

Ascending Order: [Alice, Bob, Charlie, John]
Descending Order: [John, Charlie, Bob, Alice]

3. Finding the Maximum and Minimum Values in a List

Question: Write a Java 8 program to find the maximum and minimum values in a list of integers.

Answer:

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

public class MaxMinValues {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(10, 20, 5, 30, 15);

        Optional<Integer> max = numbers.stream().max(Integer::compareTo);
        Optional<Integer> min = numbers.stream().min(Integer::compareTo);

        System.out.println("Max Value: " + max.orElse(0));
        System.out.println("Min Value: " + min.orElse(0));
    }
}

Output:

Max Value: 30
Min Value: 5

4. Grouping Objects by a Specific Property using Streams

Question: Given a list of Employee

objects, write a Java 8 program to group them by their department.

Answer:

import java.util.*;
import java.util.stream.Collectors;

class Employee {
    private String name;
    private String department;

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

    public String getDepartment() {
        return department;
    }

    @Override
    public String toString() {
        return name;
    }
}

public class GroupByDepartment {
    public static void main(String[] args) {
        List<Employee> employees = Arrays.asList(
            new Employee("John", "HR"),
            new Employee("Alice", "IT"),
            new Employee("Bob", "HR"),
            new Employee("Charlie", "IT")
        );

        Map<String, List<Employee>> groupedByDepartment = employees.stream()
            .collect(Collectors.groupingBy(Employee::getDepartment));

        System.out.println("Employees grouped by department: " + groupedByDepartment);
    }
}

Output:

Employees grouped by department: {HR=[John, Bob], IT=[Alice, Charlie]}

5. Removing Duplicates from a List using Streams

Question: Write a Java 8 program to remove duplicates from a list of integers.

Answer:

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

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

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

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

Output:

Unique Numbers: [1, 2, 3, 4, 5]

6. Counting the Frequency of Characters in a String using Streams

Question: Write a Java 8 program to count the frequency of each character in a string.

Answer:

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

public class CharacterFrequency {
    public static void main(String[] args) {
        String input = "java8";

        Map<Character, Long> frequencyMap = input.chars()
            .mapToObj(c -> (char) c)
            .collect(Collectors.groupingBy(c -> c, Collectors.counting()));

        System.out.println("Character Frequency: " + frequencyMap);
    }
}

Output:

Character Frequency: {a=2, v=1, j=1, 8=1}

Java 8 subtract N minutes from current date

  • Java 8 provides java.time.LocalDateTime class.
  • By using minusMinutes() methods of LocalDateTime class we can subtract minutes from date or current date in java.
  • Lets see an example program on how to remove / subtract n minutes from current date using java 8.



  1. package com.instanceofjava.java8;
  2. import java.time.LocalDateTime;

  3. /**
  4.  * @author www.Instanceofjava.com
  5.  * @category interview programs
  6.  * 
  7.  * Description: subtract minutes to current date using java 8
  8.  *
  9.  */
  10. public class AddMinutesToDate {

  11. public static void main(String[] args) {
  12. //create data using java 8 LocalDateTime 
  13.     LocalDateTime datetime= LocalDateTime.now();
  14. System.out.println("Before subtracting 30 minutes to date: "+datetime);
  15.     //add seconds by using minuesMinutes(seconds) method
  16. datetime=datetime.minusMinutes(30);
  17. System.out.println("After subtracting 30 minutes to date: "+datetime);

  18. }

  19. }

Output:

  1. Before subtracting 30 minutes to date: 2018-02-05T22:41:42.463
  2. After subtracting 30 minutes to date: 2018-02-05T22:11:42.463


subtract minutes from java 8 date time.png

How to Add N minutes to current date using java 8

  • Java 8 providing java java.time package which is having more utility methods related to date and time.
  • LocalDateTime class providing plusMinutes(int minutes) method to add minutes to current date or given date in java.
  • Lets see an example program to add 30 minutes to current date using java 8 LocalDateTime class.



#1: Java Example program to add 30 minutes to current date 

  1. package com.instanceofjava.java8;

  2. import java.time.LocalDateTime;

  3. /**
  4.  * @author www.Instanceofjava.com
  5.  * @category interview programs
  6.  * 
  7.  * Description: Add minutes to current date using java 8
  8.  *
  9.  */
  10. public class AddMinutesToDate {

  11. public static void main(String[] args) {
  12. //create data using java 8 LocalDateTime 
  13.     LocalDateTime datetime= LocalDateTime.now();
  14. System.out.println("Before adding minutes to date: "+datetime);
  15.     //add seconds by using plusMinutes(Minutes) method
  16. datetime=datetime.plusMinutes(30);
  17. System.out.println("After adding 30 minutes to date: "+datetime);

  18. }

  19. }



Output:


  1. Before adding minutes to date: 2018-02-05T22:14:33.664
  2. After adding 30 minutes to date: 2018-02-05T22:44:33.664



add minutes to current date java 8


Can we define default methods in functional interfaces in java 8

  • Functional interfaces in java 8 will have single abstract method in it.
  • Check below two pages regarding defining and using functional interfaces using Lamda expressions.
  • Java 8 functional interface with example
  • Implement java 8 functional interface using lambda example program
  • We can define default methods in functional interfaces in java 8.
  • But every functional interface must have single abstract method in it.
  • As we know that default methods should have a implementation as they are not abstract methods.
  • Lets see an example program on defining functional interface with default method.



#1:  Java example program to create functional interface with default method.

  1. package com.instanceofjava.java8;

  2. /**
  3.  * @author www.Instanceofjava.com
  4.  * @category interview programming questions
  5.  * 
  6.  * Description: java 8 functional interfaces
  7.  *
  8.  */
  9. @FunctionalInterface
  10. public interface FunctionalInterfaceExample {
  11.  
  12. void show();
  13.         //default method
  14. default void message() {
  15. System.out.println("hello this is default method in functional interface");
  16. }
  17. }


#2: Java Example program on how to implement functional interface abstract method and use default method.


Can we define default methods in functional interfaces in java 8


Functional interface with multiple methods in java 8

  • Functional interfaces will contains single abstract method with @FunctionalInterface annotation.
  • Check below two posts for defining functional interface and implementing functional interface method using Lamda in java 8.
  • Java 8 functional interface with example
  • Implement java 8 functional interface using lambda example program
  • Now the question is can we declare or define multiple abstract methods in one functional interface in java 8.
  • No. Functional interface should contain only one abstract method so that Lamda will implement it.
  • Lets see what happens if we define multiple abstract methods inside a functional interface
  • Note: all methods inside any interface by default abstract methods.



  1. package com.instanceofjava.java8;

  2. /**
  3.  * @author www.Instanceofjava.com
  4.  * @category interview programming questions
  5.  * 
  6.  * Description: java 8 functional interfaces
  7.  *
  8.  */
  9. @FunctionalInterface
  10. public interface FunctionalInterfaceExample {
  11. //compile time error: Invalid '@FunctionalInterface' annotation; FunctionalInterfaceExample is
  12. not a functional interface
  13.  
  14. void show();
  15. void calculate();
  16. }


  • If we define multiple abstract methods inside a functional interface it will throw a compile time error.
  • Invalid '@FunctionalInterface' annotation; FunctionalInterfaceExample is not a functional interface

Implement java 8 functional interface using lambda example program

  • Functional interfaces introduces in java 8 .
  • Functional interfaces will have single abstract method in it.
  • Check here for full details on Java 8 functional interface with example.
  • Functional interfaces will be implemented by java 8 Lamda expressions.
  • Lets see an example program on how can we use functional interfaces or how can we implement functional interfaces using Lamda expression in java 8.
  • Create one functional interface with one abstract method in it.
  • Create a class and implement this abstract method using Lamda Expressions.



#1: Java example program to create functional interface.

functional interface example in java 8 using lamda expressions


#2: Java example program to implement functional interface using Lamda expressions in java 8.

  1. package com.instanceofjava.java8;
  2. /**
  3.  * @author www.Instanceofjava.com
  4.  * @category interview programming questions
  5.  * 
  6.  * Description: java 8 Lamda expressions
  7.  *
  8.  */
  9. public class LamdaExpressions {

  10. public static void main(String[] args) {
  11. FunctionalInterfaceExample obj = ()->{
  12. System.out.println("hello world");
  13. };

  14. obj.show();
  15. }

  16. }

Output:

  1. hello world

Select Menu