DEV Community

DevCorner2
DevCorner2

Posted on

Java Stream API – Interview-Ready Code Snippets

1️⃣ Filter & Map – Capitalize Strings with Length Check

List<String> names = List.of("alice", "bob", "charlie");

List<String> result = names.stream()
    .filter(name -> name.length() > 3)
    .map(String::toUpperCase)
    .collect(Collectors.toList());

// Output: [ALICE, CHARLIE]
Enter fullscreen mode Exit fullscreen mode

2️⃣ FlatMap – Flatten Nested Lists

List<List<Integer>> nested = List.of(
    List.of(1, 2), List.of(3, 4), List.of(5)
);

List<Integer> flat = nested.stream()
    .flatMap(Collection::stream)
    .collect(Collectors.toList());

// Output: [1, 2, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

3️⃣ Group by Field – Count of Items per Category

record Product(String name, String category) {}

List<Product> products = List.of(
    new Product("Phone", "Electronics"),
    new Product("TV", "Electronics"),
    new Product("Shirt", "Clothing")
);

Map<String, Long> counts = products.stream()
    .collect(Collectors.groupingBy(
        Product::category, Collectors.counting()
    ));

// Output: {Clothing=1, Electronics=2}
Enter fullscreen mode Exit fullscreen mode

4️⃣ Find First and Fallback

List<String> list = List.of("java", "python", "go");

String result = list.stream()
    .filter(s -> s.startsWith("k"))
    .findFirst()
    .orElse("not found");

// Output: not found
Enter fullscreen mode Exit fullscreen mode

5️⃣ Map to Max by Property

record Person(String name, int age) {}

List<Person> people = List.of(
    new Person("A", 25), new Person("B", 30), new Person("C", 22)
);

Person oldest = people.stream()
    .max(Comparator.comparing(Person::age))
    .orElseThrow();

// Output: Person{name='B', age=30}
Enter fullscreen mode Exit fullscreen mode

6️⃣ Convert List to Map with Key Collision Handling

List<String> words = List.of("apple", "banana", "apricot");

Map<Character, String> result = words.stream()
    .collect(Collectors.toMap(
        w -> w.charAt(0),
        w -> w,
        (existing, replacement) -> existing + "," + replacement
    ));

// Output: {a=apple,apricot, b=banana}
Enter fullscreen mode Exit fullscreen mode

7️⃣ Sum Prices Using Reduce

record Item(String name, double price) {}

List<Item> cart = List.of(
    new Item("Pen", 1.2), new Item("Notebook", 2.5)
);

double total = cart.stream()
    .map(Item::price)
    .reduce(0.0, Double::sum);

// Output: 3.7
Enter fullscreen mode Exit fullscreen mode

8️⃣ Partition List by Condition (Even/Odd)

List<Integer> numbers = IntStream.rangeClosed(1, 10).boxed().toList();

Map<Boolean, List<Integer>> partition = numbers.stream()
    .collect(Collectors.partitioningBy(n -> n % 2 == 0));

// Output: {false=[1,3,5,7,9], true=[2,4,6,8,10]}
Enter fullscreen mode Exit fullscreen mode

9️⃣ Join Strings with Delimiter

List<String> items = List.of("one", "two", "three");

String csv = items.stream()
    .collect(Collectors.joining(", "));

// Output: one, two, three
Enter fullscreen mode Exit fullscreen mode

🔟 Custom Collector – Concatenate Uppercase with Delimiter

List<String> names = List.of("java", "go", "python");

String result = names.stream()
    .map(String::toUpperCase)
    .collect(Collectors.joining(" | "));

// Output: JAVA | GO | PYTHON
Enter fullscreen mode Exit fullscreen mode

1️⃣1️⃣ Sorting by Multiple Fields

record Employee(String name, int age) {}

List<Employee> employees = List.of(
    new Employee("John", 25),
    new Employee("Alice", 25),
    new Employee("Bob", 22)
);

List<Employee> sorted = employees.stream()
    .sorted(Comparator.comparing(Employee::age)
        .thenComparing(Employee::name))
    .collect(Collectors.toList());
Enter fullscreen mode Exit fullscreen mode

1️⃣2️⃣ Peek for Debugging (Avoid in Prod)

List<String> result = List.of("a", "b", "c").stream()
    .peek(s -> System.out.println("Before map: " + s))
    .map(String::toUpperCase)
    .peek(s -> System.out.println("After map: " + s))
    .collect(Collectors.toList());
Enter fullscreen mode Exit fullscreen mode

1️⃣3️⃣ Remove Duplicates by Custom Key

record Book(String title, String author) {}

List<Book> books = List.of(
    new Book("Book1", "A"),
    new Book("Book2", "A"), // same author
    new Book("Book3", "B")
);

Collection<Book> uniqueAuthors = books.stream()
    .collect(Collectors.toMap(
        Book::author,
        Function.identity(),
        (existing, replacement) -> existing
    ))
    .values();

// Output: Book1, Book3 (1 per author)
Enter fullscreen mode Exit fullscreen mode

1️⃣4️⃣ Collect to Unmodifiable List

List<String> list = Stream.of("x", "y", "z")
    .collect(Collectors.collectingAndThen(
        Collectors.toList(),
        Collections::unmodifiableList
    ));
Enter fullscreen mode Exit fullscreen mode

1️⃣5️⃣ Stream + Optional + Chaining

Optional<String> longest = Stream.of("apple", "pear", "banana")
    .filter(s -> s.length() > 4)
    .max(Comparator.comparing(String::length));

// Output: Optional[banana]
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.