Which useful String, Stream and Optional methods were added after Java 8?

Java 9 to 21 added many small methods that make everyday code shorter. Interviewers often ask about them to check whether a candidate has moved beyond Java 8.

Key Points: • String (Java 11): isBlank(), strip(), stripLeading(), stripTrailing(), lines(), repeat(n). Java 12 added indent() and transform(). • strip() is Unicode-aware, unlike trim(), which only removes characters up to the space character. • Stream: takeWhile() and dropWhile() (Java 9), Stream.ofNullable() (Java 9) and toList() (Java 16). • Collectors.teeing() (Java 12) combines two collectors into one result. • Optional: or() and ifPresentOrElse() (Java 9), orElseThrow() without arguments (Java 10) and isEmpty() (Java 11). • List.of(), Set.of() and Map.of() (Java 9) create immutable collections.

Code Example:

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class NewMethodsDemo {

    public static void main(String[] args) {
        System.out.println("   ".isBlank());
        System.out.println("[" + "  java  ".strip() + "]");
        System.out.println("ab".repeat(3));
        System.out.println("line1\nline2\nline3".lines().count());

        List<Integer> nums = List.of(1, 2, 3, 10, 4, 5);
        System.out.println(nums.stream().takeWhile(n -> n < 10).toList());
        System.out.println(nums.stream().dropWhile(n -> n < 10).toList());

        double avg = Stream.of(10, 20, 30).collect(Collectors.teeing(
                Collectors.summingInt(n -> n), Collectors.counting(),
                (sum, count) -> (double) sum / count));
        System.out.println("Average: " + avg);

        Optional<String> empty = Optional.empty();
        empty.ifPresentOrElse(System.out::println, () -> System.out.println("No value"));
        System.out.println(empty.isEmpty());
    }
}

Output:

true [java] ababab 3 [1, 2, 3] [10, 4, 5] Average: 20.0 No value true

Good to Know: A favourite follow-up is "What is the difference between trim() and strip()?" trim() removes characters with code up to U+0020. strip() uses Character.isWhitespace(), so it also removes Unicode spaces such as the non-breaking space found in copied text.

Interview Tip: A concise interview answer is:

"After Java 8, String gained isBlank, strip, lines and repeat; Stream gained takeWhile, dropWhile and toList; Optional gained ifPresentOrElse, isEmpty and orElseThrow; and Collectors.teeing was added. I also mention List.of and Map.of for immutable collections."

Previous question: What are sequenced collections in Java 21?

Next question: What is the Java 11 HttpClient, and how is it better than HttpURLConnection?

More Java 17 and 21 Features interview questions

All Java 17 and 21 Features questions