Java 8 Stream API — Interview Q&A with Real Examples

Java 8 Stream API — Interview Q&A with Real Examples

In this post, we explore commonly asked Java 8 Stream API interview questions with practical examples and explanations. Ideal for both freshers and experienced developers.

👨‍🏫 Let’s first define a sample 

Account class: Account.java

Before we dive into Java 8 examples, let’s define the class we’ll be using in all code samples:

public class Account {
    private String id;
    private String name;
    private String type; 
    private double balance;
    private boolean active;

    // Constructor
    public Account(String id, String name, String type, double balance, boolean active) {
        this.id = id;
        this.name = name;
        this.type = type;
        this.balance = balance;
        this.active = active;
    }
    // Getters/Setters
}

Now that we have a real-world Account object, let’s learn how to use Java 8 Stream API to solve common interview and production use-cases.


Q1: How do you filter a list of accounts where the balance is greater than 10,000?

Answer: We use the filter() method to keep only those accounts that match the condition.

List<Account> richAccounts = accounts.stream()
    .filter(acc -> acc.getBalance() > 10000) // keep only accounts with balance > 10,000
    .collect(Collectors.toList());           // convert the filtered stream back to a list

Q2: How do you extract just account IDs from a list of Account objects?

Answer: We use map() to transform each Account into its ID.

List<String> accountIds = accounts.stream()
    .map(Account::getId)                    // convert Account to String (ID)
    .collect(Collectors.toList());          // collect IDs into a list

Q3: How do you merge multiple lists of accounts into one?

Answer: Use Stream.of() to create a stream of lists, and flatMap() to flatten them into one stream.

List<Account> merged = Stream.of(list1, list2, list3)  // creates a stream of 3 lists
    .flatMap(Collection::stream)                       // flattens the lists into a single stream of Account
    .collect(Collectors.toList());                     // collect into a single merged list

Q4: How do you get distinct account types from a list?

Answer: We first map to types, then call distinct() to eliminate duplicates.

List<String> types = accounts.stream()
    .map(Account::getType)              // extract the account type from each Account
    .distinct()                         // remove duplicates
    .collect(Collectors.toList());      // collect into a list

Q5: How do you find the account with the maximum balance?

Answer: Use max() with a custom comparator based on balance.

Optional<Account> richest = accounts.stream()
    .max(Comparator.comparing(Account::getBalance));  // find the Account with the highest balance

Optional is returned to handle the case where the list may be empty.


Q6: How do you group accounts by type?

Answer: We use Collectors.groupingBy() to group elements based on a classifier function.

Map<String, List<Account>> grouped = accounts.stream()
    .collect(Collectors.groupingBy(Account::getType));  // group accounts into a map by account type

Q7: How do you sum all account balances?

Answer: Use mapToDouble() to extract balances and then call sum().

double total = accounts.stream()
    .mapToDouble(Account::getBalance)  // convert Account to primitive double stream
    .sum();                            // sum all the balances

Q8: Can you convert a list of accounts to a Map of ID to Account?

Answer: Use Collectors.toMap() with the key as ID and value as the object itself.

Map<String, Account> map = accounts.stream()
    .collect(Collectors.toMap(Account::getId, Function.identity()));
    // key = ID, value = Account object

Q9: How do you handle duplicate keys in 

Collectors.toMap() ?

Answer: By providing a merge function that resolves which value to keep.

Map<String, Account> map = accounts.stream()
    .collect(Collectors.toMap(
        Account::getId,               // key = account ID
        Function.identity(),          // value = Account object
        (a1, a2) -> a1                // if key duplicates, keep the first one
    ));

Without a merge function, toMap() will throw IllegalStateException on duplicate keys.


🔚 Summary

Java 8 Stream API allows us to work with collections in a functional way. In interviews, these are some of the most asked questions. Be ready to not just code, but also explain how each method (map, filter, flatMap, collect, groupingBy, toMap, etc.) works and why we use it in each context.