You are here
Home > java > Core Java >

Java 8 Coding Interview Questions

Java 8 coding interview questions covering Streams, Strings, Collections, Dates, and Map operations.In this article, We will discuss about Java 8 Coding Interview Questions and their Answers. Moreover, we will try to provide multiple approaches to solve a coding problem. Additionally, related concepts to a particular coding problem will also be discussed. Our primary focus of this article is to provide all important Java 8 Coding Interview Questions and their Answers. However, for theoretical questions & answers of Java 8 Interview, kindly visit our other article ‘Java 8 Concept Based Interview Questions & Answers.

Java 8 Coding Interview Questions

In the subsequent sections of this article, we will discuss the important coding questions using Java 8 or higher versions. If you want to go through detailed tutorial on Java 8 Features, you may visit Concepts Tutorial on Java 8 Features.

You may also check Quizzes/MCQs on Java & related framework at Java Practice Test & Interview Questions .

For Java 17 interview questions, kindly refer Java 17 Coding Interview Questions & Solutions.

How to iterate and modify values in a Map using Java 8?

Use computeIfPresent to change a value only when the key exists, computeIfAbsent to add one only when it does not, and replaceAll to rewrite every value. Iterate with Map.forEach.Here is the program to update & iterate a Map in Java 8.

import java.util.HashMap;
import java.util.Map;

public class MapUpdateTest {

    public static void main(String[] args) {
        Map<String, String> map = new HashMap<>();
        map.put("Effective Java", "Kathy Sierra");   
        map.put("Spring in Action", "Craig Walls");
        map.put("Hibernate in Action", "Gavin King");
        map.put("Pro Angular", "Freeman");
        map.put("Pro Spring Boot", "Felipe Gutierrez");

        // Update only if the key already exists
        map.computeIfPresent("Effective Java", (key, oldValue) -> "Joshua Bloch");

        // Add only if the key is absent (the function receives the KEY, not a value)
        map.computeIfAbsent("Core Java", key -> "Kathy Sierra");

        // Iterate and print
        map.forEach((title, author) -> System.out.println(title + "=" + author));

        // Modify every value in one pass
        map.replaceAll((title, author) -> author.toUpperCase());
        System.out.println(map.get("Core Java"));
    }
}

Output:

HashMap makes no ordering promise, so the order can differ on another JDK; use LinkedHashMap or TreeMap when order matters

Hibernate in Action=Gavin King
Core Java=Kathy Sierra
Pro Angular=Freeman
Effective Java=Joshua Bloch
Pro Spring Boot=Felipe Gutierrez
Spring in Action=Craig Walls
KATHY SIERRA

How to print keys & values of a Map using Java 8 ?

In Java 8, call map.forEach((key, value) -> …). keySet() returns a Set of the keys, and values() returns a Collection of the values (not a Set, because values can repeat).

import java.util.HashMap;
import java.util.Map;

public class MapPrintJava8 {

    public static void main(String[] args) {
        Map<String, String> map = new HashMap<>();
        map.put("Core Java", "Kathy Sierra");
        map.put("Spring in Action", "Craig Walls");

        map.forEach((title, author) -> System.out.println(title + " = " + author));  // keys and values
        map.keySet().forEach(System.out::println);                                    // keys only (a Set)
        map.values().forEach(System.out::println);                                    // values only (a Collection)
    }
}

Output:

the first two lines are the pairs, the next two the keys, the last two the values.

Core Java = Kathy Sierra
Spring in Action = Craig Walls
Core Java
Spring in Action
Kathy Sierra
Craig Walls
1) Using  Collection.iterator() and Iterator.forEachRemaining()
map.keySet().iterator()
     .forEachRemaining(System.out::println);
2) Using Collection.stream() and Stream.forEach()
map.values().stream().forEach(System.out::println);
3) Using Stream.of() and  Collection.toArray() and Stream.forEach()
Stream.of(map.keySet().toArray()).forEach(System.out::println);

4) Using Stream.of() and  Collection.toString() and Stream.forEach()

Stream.of(map.values().toString()).forEach(System.out::println);

How many ways are there to print keys & values of a Map?

Five, listed below. Pick by what else you need to do with the entries.

Approach Use it when
Map.forEach((k, v) -> …) Java 8 or newer and you only need the key and value
for-each loop over entrySet() any Java version; the readable default
explicit Iterator over entrySet() you must remove entries while iterating
entrySet().stream() you also sort, filter or map the entries
keySet() loop with get() avoid: it does an extra lookup per key
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class MapPrintWays {

    public static void main(String[] args) {
        Map<String, String> map = new HashMap<>();
        map.put("Core Java", "Kathy Sierra");
        map.put("Spring in Action", "Craig Walls");

        // 1. Java 8: Map.forEach with a BiConsumer (shortest, no Entry needed)
        map.forEach((k, v) -> System.out.println("1) " + k + " = " + v));

        // 2. for-each over entrySet (works on every Java version)
        for (Map.Entry<String, String> e : map.entrySet()) {
            System.out.println("2) " + e.getKey() + " = " + e.getValue());
        }

        // 3. Explicit Iterator (needed when you must remove entries while iterating)
        Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, String> e = it.next();
            System.out.println("3) " + e.getKey() + " = " + e.getValue());
        }

        // 4. Java 8 stream over entrySet (use it when you also filter, sort or map)
        map.entrySet().stream()
           .sorted(Map.Entry.comparingByKey())
           .forEach(e -> System.out.println("4) " + e.getKey() + " = " + e.getValue()));

        // 5. keySet() loop plus get(): works, but does an extra lookup per key
        for (String k : map.keySet()) {
            System.out.println("5) " + k + " = " + map.get(k));
        }
    }
}

Output (the number at the start of each line is the way used):

1) Core Java = Kathy Sierra
1) Spring in Action = Craig Walls
2) Core Java = Kathy Sierra
2) Spring in Action = Craig Walls
3) Core Java = Kathy Sierra
3) Spring in Action = Craig Walls
4) Core Java = Kathy Sierra
4) Spring in Action = Craig Walls
5) Core Java = Kathy Sierra
5) Spring in Action = Craig Walls

You may see Stream.of(map.entrySet().toString()) listed as another way. It prints the whole map as one string and does not iterate the entries, so it is not a real way.

What it tests: choosing an approach by need. Common mistake: option 5 looks natural but does an extra lookup for every key; prefer entrySet(). Likely follow-up: remove entries while iterating. Use the iterator’s remove() or map.entrySet().removeIf(…); removing directly from the map inside a loop throws ConcurrentModificationException.

How to convert String to Date Object using Java 8 ?

Below code demonstrates the concept. Here we can convert a String to four forms of a Date.
1) String to java.util.Date
2) String to java.time.LocalDate
3) String to java.time.LocalDateTime
4) String to java.time.ZonedDateTime
Prefer java.time: use LocalDate.parse, LocalDateTime.parse or ZonedDateTime.parse with a DateTimeFormatter. SimpleDateFormat still works for the old java.util.Date, but it is not thread-safe.
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Date;
import java.util.Locale;

public class StringToDate {

    public static void main(String[] args) throws ParseException {

        // String to java.util.Date (legacy API; SimpleDateFormat is not thread-safe)
        SimpleDateFormat dateFormatter = new SimpleDateFormat("dd-MMM-yyyy hh:mm:ss a", Locale.ENGLISH);
        Date date = dateFormatter.parse("24-May-2021 9:45:30 AM");
        System.out.println(date);

        // String to java.time.LocalDate
        System.out.println(LocalDate.parse("2021-05-24"));

        // String to java.time.LocalDateTime
        System.out.println(LocalDateTime.parse("2021-05-24T21:45:30"));

        // String to java.time.ZonedDateTime
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss z");
        System.out.println(ZonedDateTime.parse("2021-05-24 21:45:30 America/New_York", formatter));

        // Custom pattern with java.time (DateTimeFormatter is immutable and thread-safe)
        DateTimeFormatter custom = DateTimeFormatter.ofPattern("d-MMM-yyyy h:mm:ss a", Locale.ENGLISH);
        System.out.println(LocalDateTime.parse("24-May-2021 9:45:30 AM", custom));

        // A pattern mismatch throws DateTimeParseException
        try {
            LocalDate.parse("24-05-2021");
        } catch (DateTimeParseException e) {
            System.out.println(e.getMessage());
        }
    }
}

Output

the first line prints in your JVM’s default time zone, so yours may show a different zone; the last line is the DateTimeParseException message for a pattern mismatch.

Mon May 24 09:45:30 UTC 2021
2021-05-24
2021-05-24T21:45:30
2021-05-24T21:45:30-04:00[America/New_York]
2021-05-24T09:45:30
Text '24-05-2021' could not be parsed at index 0

What it tests: the legacy Date API versus java.time. Common mistake: sharing one static SimpleDateFormat between threads. Its documentation says date formats are not synchronized and recommends a separate instance per thread, and the JDK source suggests DateTimeFormatter as the immutable, thread-safe alternative (OpenJDK source change). Likely follow-up: convert the parsed value to another time zone.

How many ways are there to initialize a Set ?

Five: the constructor with Arrays.asList, a stream with Collectors.toCollection, Set.of (Java 9+), a read-only view with Collections.unmodifiableSet, and double-brace initialization, which you should avoid.

import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class SetInitialization {

    public static void main(String[] args) {
        // 1. Constructor plus Arrays.asList (all Java versions)
        Set<String> s1 = new HashSet<>(Arrays.asList("California", "Chicago", "New York"));

        // 2. Stream plus Collectors.toCollection (Java 8): you choose the Set type
        Set<String> s2 = Stream.of("California", "Chicago", "New York")
                .collect(Collectors.toCollection(TreeSet::new));

        // 3. Set.of (Java 9+): immutable, no nulls, no duplicates, iteration order unspecified
        Set<String> s3 = Set.of("California", "Chicago", "New York");

        // 4. Read-only view of an existing set (Java 8)
        Set<String> s4 = Collections.unmodifiableSet(s1);

        // 5. Double-brace initialization: it works, but avoid it
        Set<String> s5 = new HashSet<String>() {{ add("California"); add("Chicago"); }};

        System.out.println(s2);
        System.out.println(s5.getClass() == HashSet.class);   // false: it is an anonymous subclass
        try {
            s3.add("Boston");
        } catch (UnsupportedOperationException e) {
            System.out.println("Set.of(...) is immutable");
        }
        try {
            Set.of("a", "b", "a");
        } catch (IllegalArgumentException e) {
            System.out.println(e.getMessage());
        }
    }
}

Output:

false shows that the double-brace set is an anonymous subclass of HashSet, not a HashSet.

[California, Chicago, New York]
false
Set.of(...) is immutable
duplicate element: a

What it tests: mutable versus immutable sets. Common mistake: Set.of throws IllegalArgumentException for a repeated element (last line) and UnsupportedOperationException if you add to it (third line), and its iteration order is unspecified. Double-brace initialization also creates an extra anonymous class for every use. Likely follow-up: if the original set changes later, does the Collections.unmodifiableSet view change too?

How to create various collections using Factory Method of Java 9 ?

Java 9 added List.of, Set.of and Map.of (plus Map.ofEntries) to create immutable collections in one line. They need Java 9 or newer. Map.of has overloads for up to 10 key-value pairs (an 11th pair does not compile); beyond that, use Map.ofEntries(Map.entry(k, v), …).
FactoryMethods.java (Java 9+)
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class FactoryMethods {

    public static void main(String[] args) {
        List<String> list = List.of("USA", "Canada", "Russia");
        Set<String> set = Set.of("USA", "Canada", "Russia");
        Map<String, String> map = Map.of("USA", "Washington, D.C.", "Canada", "Ottawa", "Russia", "Moscow");

        // Map.of takes at most 10 key-value pairs. For more, use Map.ofEntries
        Map<Integer, String> many = Map.ofEntries(Map.entry(1, "one"), Map.entry(2, "two"));

        try { list.add("Brazil"); } catch (UnsupportedOperationException e) {
            System.out.println("List.of(...) is immutable");
        }
        try { List.of("a", null); } catch (NullPointerException e) {
            System.out.println("List.of(...) rejects null");
        }
        try { Map.of("k", "v", "k", "w"); } catch (IllegalArgumentException e) {
            System.out.println(e.getMessage());
        }

        // Arrays.asList is different: fixed size, but elements can be replaced
        List<String> fixed = Arrays.asList("a", "b");
        fixed.set(0, "z");
        try { fixed.add("c"); } catch (UnsupportedOperationException e) {
            System.out.println("Arrays.asList(...) cannot grow");
        }
        System.out.println(fixed);
    }
}

Output:

List.of(...) is immutable
List.of(...) rejects null
duplicate key: k
Arrays.asList(...) cannot grow
[z, b]

What it tests: the immutability rules. Common mistake: treating List.of like Arrays.asList. List.of is fully immutable and rejects null; Arrays.asList has a fixed size but lets you replace elements (the last line shows [z, b]). Likely follow-up: Set.of and Map.of throw IllegalArgumentException for a repeated element or key (third line).


How to retrieve values from Set using Java 8 ?

In order to retrieve values from a Set using Java 8, we can use Stream API of Java 8. Moreover, we must create a Stream from the Set and then iterate the Stream. For example, below code demonstrates the concept.

Call set.forEach(System.out::println). Create a stream only when you also need to filter, map or sort.

import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;

public class SetValuesRetrieval {

    public static void main(String[] args) {
        Set<String> set = new HashSet<>();
        set.add("California");
        set.add("Chicago");
        set.add("New York");

        // Simplest: Iterable.forEach, no stream needed
        set.forEach(System.out::println);

        // Use a stream only when you also filter, map or sort
        System.out.println(set.stream()
                .filter(s -> s.startsWith("C"))
                .sorted()
                .collect(Collectors.toList()));
    }
}

Output (the first three lines come out in HashSet hash order, not insertion order):

New York
Chicago
California
[California, Chicago]

What it tests: Iterable.forEach versus stream().forEach. Common mistake: relying on HashSet order in a test or an answer. Use LinkedHashSet for insertion order or TreeSet for sorted order. Likely follow-up: print the set sorted.

How to iterate a Map containing a List of String in Java 8 ?

Iterate the map with forEach, where each value is a list. Use flatMap(List::stream) when you need all the list items in one stream.

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

public class IterateMapOfList {

    public static void main(String[] args) {
        Map<String, List<String>> animals = new HashMap<>();
        animals.put("Mammals", Arrays.asList("Cat", "Dog", "Monkey", "Cow"));
        animals.put("Birds", Arrays.asList("Crow", "Parrot", "Peacock", "Flamingo"));
        animals.put("Reptiles", Arrays.asList("Lizard", "Turtle", "Crocodile", "Python"));

        // Iterate the map: key = category, value = list of animals
        animals.forEach((category, list) ->
                System.out.println("Category: " + category + " -> " + list));

        // Flatten every list into one sorted list
        List<String> all = animals.values().stream()
                .flatMap(List::stream)
                .sorted()
                .collect(Collectors.toList());
        System.out.println(all);
    }
}

Output:

Category: Reptiles -> [Lizard, Turtle, Crocodile, Python]
Category: Birds -> [Crow, Parrot, Peacock, Flamingo]
Category: Mammals -> [Cat, Dog, Monkey, Cow]
[Cat, Cow, Crocodile, Crow, Dog, Flamingo, Lizard, Monkey, Parrot, Peacock, Python, Turtle]

What it tests: nested collections and flatMap. Common mistake: lists created with Arrays.asList have a fixed size, so add throws UnsupportedOperationException (see the factory-methods question). Likely follow-up: the total number of animals across all categories.

How to count occurrences of each character of a String in Java 8?

For example, let’s assume a string “JAVA PROGRAMMER”. Now, we have to count occurrences of each character in this string including spaces. We are including space also, so that we do this exercise for a sentence as well using this program.
Group the characters by themselves and count each group: Collectors.groupingBy(Function.identity(), TreeMap::new, Collectors.counting()) returns a sorted Map<Character, Long> in one pass. The string includes a space, so the same code works on a sentence.
import java.util.Map;
import java.util.TreeMap;
import java.util.function.Function;
import java.util.stream.Collectors;

public class CharactersCountTest {

    public static void main(String[] args) {
        String text = "JAVA PROGRAMMER";

        Map<Character, Long> counts = text.chars()
                .mapToObj(c -> (char) c)
                .collect(Collectors.groupingBy(Function.identity(), TreeMap::new, Collectors.counting()));

        counts.forEach((ch, n) -> System.out.println("Occurrences of '" + ch + "' : " + n));

        // chars() works on UTF-16 units, so an emoji counts twice; codePoints() counts it once
        String withEmoji = "a\uD83D\uDE00";   // 'a' followed by a grinning-face emoji
        System.out.println(withEmoji.chars().count() + " vs " + withEmoji.codePoints().count());
    }
}

Output (the last line compares chars() and codePoints() for a string that contains an emoji):

Occurrences of ' ' : 1
Occurrences of 'A' : 3
Occurrences of 'E' : 1
Occurrences of 'G' : 1
Occurrences of 'J' : 1
Occurrences of 'M' : 2
Occurrences of 'O' : 1
Occurrences of 'P' : 1
Occurrences of 'R' : 3
Occurrences of 'V' : 1
3 vs 2

What it tests: groupingBy with a downstream collector. Common mistake: counting each distinct character with its own filter(…).count() rescans the string once per character. Also, chars() returns UTF-16 units, so an emoji counts as 2 (last line: 3 vs 2). Use codePoints() when the text can contain emoji. Likely follow-up: make it case-insensitive (toLowerCase() first) or keep the input order (LinkedHashMap::new).


How to find next/previous(tomorrow/yesterday) date using Java 8?

Use LocalDate.plusDays(1) and minusDays(1). They handle month ends, year ends and leap years for you.
import java.time.LocalDate;

public class NextPreviousDate {

    static LocalDate nextDay(LocalDate date) {
        return date.plusDays(1);
    }

    static LocalDate previousDay(LocalDate date) {
        return date.minusDays(1);
    }

    public static void main(String[] args) {
        LocalDate day = LocalDate.of(2026, 11, 25);
        System.out.println(nextDay(day) + " / " + previousDay(day));
        System.out.println(nextDay(LocalDate.of(2028, 2, 28)));        // leap year
        System.out.println(nextDay(LocalDate.of(2026, 12, 31)));       // year rollover
        System.out.println(LocalDate.of(2026, 3, 31).minusMonths(1));  // day is clamped to month end
    }
}

Output (line 2 is a leap year, line 3 a year rollover, line 4 shows the day being clamped to the end of the month):

2026-11-26 / 2026-11-24
2028-02-29
2027-01-01
2026-02-28

What it tests: that java.time objects are immutable. Common mistake: calling date.plusDays(1); and ignoring the result. It returns a new LocalDate and leaves the original unchanged. Likely follow-up: make the code testable by passing a Clock to LocalDate.now(clock).

How to remove all duplicates from an array of integers in Java using Java 8?

Call distinct() on the stream and collect back into an array. The output keeps the first occurrence of each value, so the original order is preserved.

import java.util.Arrays;
import java.util.LinkedHashSet;

public class RemoveDuplicates {

    public static void main(String[] args) {
        Integer[] array = {5, 10, 3, 7, 2, 10, 5};

        Integer[] distinct = Arrays.stream(array)
                .distinct()
                .toArray(Integer[]::new);
        System.out.println("Distinct elements: " + Arrays.toString(distinct));

        // Primitive array: no boxing needed
        int[] primitives = {5, 10, 3, 7, 2, 10, 5};
        System.out.println(Arrays.toString(Arrays.stream(primitives).distinct().toArray()));

        // Same idea without streams
        System.out.println(new LinkedHashSet<>(Arrays.asList(array)));
    }
}
Distinct elements: [5, 10, 3, 7, 2]
[5, 10, 3, 7, 2]
[5, 10, 3, 7, 2]

What it tests: distinct() and the array constructor reference Integer[]::new. Common mistake: Arrays.stream(int[]) returns an IntStream; call .boxed() only if you need an Integer[] (the second line of the program avoids boxing). Likely follow-up: how does distinct() decide that two elements are equal? It uses equals() and hashCode(), so your own classes need both.

How to count the number of occurrences of a given word in a list of strings using Java 8?

Split every string into words, flatten with flatMap, keep the words equal to the target and count them. Here is the program:

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

public class WordCount {

    public static void main(String[] args) {
        List<String> strings = Arrays.asList("java scala ruby", "java react spring java");
        String word = "java";

        long count = strings.stream()
                .flatMap(s -> Arrays.stream(s.split("\\s+")))
                .filter(w -> w.equals(word))
                .count();
        System.out.println("Occurrences of \"" + word + "\": " + count);

        // Case-insensitive variant
        List<String> mixed = Arrays.asList("Java java JAVA", "scala");
        long ignoreCase = mixed.stream()
                .flatMap(s -> Arrays.stream(s.split("\\s+")))
                .filter(word::equalsIgnoreCase)
                .count();
        System.out.println(ignoreCase);

        // If every word is already its own list element
        System.out.println(Collections.frequency(Arrays.asList("java", "scala", "java"), word));
    }
}

Output:

line 1 is case-sensitive, line 2 is the case-insensitive variant, line 3 uses Collections.frequency.

Occurrences of "java": 3
3
2

What it tests: flatMap. Common mistake: split(” “) creates empty tokens when two spaces separate words ([java, , scala]); split(“\\s+”) does not. Likely follow-up: count every word at once with groupingBy(Function.identity(), counting()).

How to filter an array of strings by a given prefix using Java 8 Stream?

Stream the array, keep the elements where startsWith(prefix) is true, and collect with toArray(String[]::new).

import java.util.Arrays;

public class StringPrefixFilter {

    public static void main(String[] args) {
        String[] strings = {"java", "scala", "javascript", "ruby", "spring", "angular", "Jakarta"};
        String prefix = "j";

        String[] filtered = Arrays.stream(strings)
                .filter(s -> s.startsWith(prefix))
                .toArray(String[]::new);
        System.out.println("Filtered strings: " + Arrays.toString(filtered));

        // Case-insensitive: "Jakarta" now matches too
        String[] ignoreCase = Arrays.stream(strings)
                .filter(s -> s.regionMatches(true, 0, prefix, 0, prefix.length()))
                .toArray(String[]::new);
        System.out.println("Ignoring case: " + Arrays.toString(ignoreCase));
    }
}

Output:

Filtered strings: [java, javascript]
Ignoring case: [java, javascript, Jakarta]

What it tests: converting an array to a stream and the array constructor reference. Common mistake: startsWith is case-sensitive, so Jakarta is missed; the second pipeline uses regionMatches(true, …) to ignore case. A null element throws NullPointerException. Likely follow-up: filter by suffix, or with a regular expression.

Write a Java program using Stream to create a map from a list of strings where the key is the string and the value is its length?

Use Collectors.toMap(keyFunction, valueFunction). It throws IllegalStateException when two elements produce the same key, so pass a merge function when duplicates are possible.

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

public class StreamToMap {

    public static Map<String, Integer> mapToLength(List<String> list) {
        return list.stream()
                .collect(Collectors.toMap(s -> s, String::length));
    }

    public static void main(String[] args) {
        List<String> names = Arrays.asList("java", "scala", "javascript", "ruby");
        System.out.println(mapToLength(names));

        // Duplicate keys: toMap throws unless you supply a merge function
        List<String> withDuplicate = Arrays.asList("java", "scala", "java");
        try {
            mapToLength(withDuplicate);
        } catch (IllegalStateException e) {
            System.out.println(e.getMessage());
        }

        // Fix: a merge function, plus LinkedHashMap to keep the input order
        Map<String, Integer> safe = withDuplicate.stream()
                .collect(Collectors.toMap(Function.identity(), String::length, (a, b) -> a, LinkedHashMap::new));
        System.out.println(safe);
    }
}

Output:

line 2 is the exception message, line 3 is the fixed version:

{java=4, scala=5, javascript=10, ruby=4}
Duplicate key java (attempted merging values 4 and 4)
{java=4, scala=5}

What it tests: that toMap fails on duplicate keys, and that the default result is a HashMap, so the order is not guaranteed. Common mistake: using toMap on data that can contain duplicates without a merge function. Likely follow-up: keep the input order (LinkedHashMap::new, shown) or keep the larger value on a clash.

How to filter and collect a list of strings that start with a specific letter using Java 8 Stream?

Filter with startsWith and collect with Collectors.toList().

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

public class StreamFilter {

    public static List<String> filterStrings(List<String> list, char letter) {
        return list.stream()
                .filter(s -> s.startsWith(String.valueOf(letter)))
                .collect(Collectors.toList());
    }

    public static void main(String[] args) {
        List<String> names = Arrays.asList("java", "scala", "javascript", "ruby");
        System.out.println(filterStrings(names, 'j'));
    }
}

Output:

[java, javascript]

Java 16 added Stream.toList(), which returns an unmodifiable list.

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

public class StreamToListJava16 {

    public static void main(String[] args) {
        List<String> names = Arrays.asList("java", "scala", "javascript", "ruby");
        List<String> result = names.stream()
                .filter(s -> s.startsWith("j"))
                .toList();                                  // Java 16+
        System.out.println(result);
        try {
            result.add("jruby");
        } catch (UnsupportedOperationException e) {
            System.out.println("Stream.toList() returns an unmodifiable list");
        }
    }
}
[java, javascript]
Stream.toList() returns an unmodifiable list

What it tests: filter and collect pipelines. Common mistake: adding to the result of Stream.toList() throws UnsupportedOperationException (second output line). Collectors.toList() makes no promise about whether the list is mutable. Likely follow-up: what is the difference between Stream.toList() and Collectors.toList()?

How to sort a list of strings by length using Lambda expressions?

Pass a comparator to List.sort. Comparator.comparingInt(String::length) is the readable Java 8 form of the lambda (a, b) -> Integer.compare(a.length(), b.length()).

import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class LambdaSort {

    public static void sortByLength(List<String> list) {
        Collections.sort(list, (a, b) -> Integer.compare(a.length(), b.length()));
    }

    public static void main(String[] args) {
        List<String> names = Arrays.asList("java", "scala", "javascript", "ruby");
        sortByLength(names);
        System.out.println(names);

        // Same result, shorter (Java 8): Comparator.comparingInt
        List<String> again = Arrays.asList("java", "scala", "javascript", "ruby");
        again.sort(Comparator.comparingInt(String::length));
        System.out.println(again);

        // Longest first, ties broken alphabetically
        List<String> longestFirst = Arrays.asList("java", "scala", "javascript", "ruby");
        longestFirst.sort(Comparator.comparingInt(String::length).reversed()
                .thenComparing(Comparator.naturalOrder()));
        System.out.println(longestFirst);

        // A read-only list cannot be sorted in place
        try {
            Collections.unmodifiableList(Arrays.asList("b", "a")).sort(null);
        } catch (UnsupportedOperationException e) {
            System.out.println("read-only list cannot be sorted in place");
        }
    }
}

Output:

Lines 1 and 2 are the same result, line 3 sorts longest first with an alphabetical tie-break, line 4 is the exception for a read-only list.

[java, ruby, scala, javascript]
[java, ruby, scala, javascript]
[javascript, scala, java, ruby]
read-only list cannot be sorted in place

What it tests: comparators. Common mistake: sorting a read-only list throws UnsupportedOperationException (line 4). Sorting is stable: java stays before ruby because both have length 4 and java came first. The Collections Javadoc documents Collections.sort as stable, and the Oracle Java Tutorials describe the same. Likely follow-up: sort by length, then alphabetically (line 3).

How to find the maximum value in a list of integers using Stream & Method Refrerence?

numbers.stream().max(Integer::compare) returns an Optional<Integer>, which is empty when the list is empty.

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

public class StreamMax {

    public static Optional<Integer> findMax(List<Integer> numbers) {
        return numbers.stream()
                .max(Integer::compare);
    }

    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(12, 42, 36, 54, 35);
        System.out.println(findMax(numbers).orElse(-1));

        // Empty list: you get Optional.empty(), not an exception
        System.out.println(findMax(Collections.<Integer>emptyList()));

        // orElse(-1) cannot tell "empty list" from "the maximum really is -1"
        System.out.println(findMax(Collections.<Integer>emptyList()).orElse(-1)
                + " " + findMax(Arrays.asList(-1)).orElse(-1));

        // Collections.max throws on an empty collection
        try {
            Collections.max(Collections.<Integer>emptyList());
        } catch (NoSuchElementException e) {
            System.out.println("Collections.max throws NoSuchElementException");
        }

        // Primitive stream: no boxing, returns OptionalInt
        System.out.println(numbers.stream().mapToInt(Integer::intValue).max().getAsInt());
    }
}

This code uses Java 8 Streams & Method Reference to find the maximum value in a list of integers.

Output:

Line 3 shows an empty list and a real maximum of -1 giving the same answer; line 4 is the Collections.max exception; line 5 uses a primitive stream:

54
Optional.empty
-1 -1
Collections.max throws NoSuchElementException
54

What it tests: Optional handling and method references. Common mistake: orElse(-1) hides the problem, because an empty list and a list whose real maximum is -1 give the same answer (line 3). Collections.max throws NoSuchElementException on an empty collection (line 4). Java 10 and newer also have Optional.orElseThrow() with no argument, which throws NoSuchElementException with the message “No value present”. Likely follow-up: use mapToInt(…).max() to avoid boxing (line 5).

Other Coding Interview Questions References

Topic Reference Link
Java 17 Coding Interview Questions and Answers Java 17 Coding Interview Questions and Answers 
Java 21 Coding Interview Questions and Answers Java 21 Coding Interview Questions and Answers
Java, Spring, Microservices Interview QnA Java, Spring, Microservices & others Interview QnA
Spring Boot Annotations Questions & Answers Spring Boot Annotations MCQs & Explanations

 

5 thoughts on “Java 8 Coding Interview Questions”

  1. Write a program using Java 8 streams to find second highest Integer in a given array of 11,13,65,76,45,98,123,100,111,44 ?

  2. int[] integerArray = {11,13,65,76,45,98,123,100,111,44};

    int secondHigest = Arrays.stream(integerArray).boxed().sorted(Comparator.reverseOrder()).limit(2).skip(1).findFirst().get();

    System.out.println(“secondHigest number is ” + secondHigest);

Leave a Reply



Top