Find Longest String in Java 8 with Reduce

Day 4 of Java Series 👉 Find the Longest String using Java 8 Streams (reduce) Java 8 introduced powerful Stream APIs, and one of the most underrated methods is reduce() — perfect for aggregating results. 💡 Problem: Find the longest string from a given list. 💻 Solution: import java.util.*; public class LongestStringUsingReduce { public static void main(String[] args) { List<String> list = Arrays.asList("Java", "Microservices", "Spring", "Docker"); String longest = list.stream() .reduce((word1, word2) -> word1.length() > word2.length() ? word1 : word2) .orElse(""); System.out.println("Longest String: " + longest); } } 🧠 How it works: stream() → Converts list into stream reduce() → Compares two elements at a time (word1, word2) -> ... → Keeps the longer string orElse("") → Handles empty list safely Finally returns the longest string ⚡ Time Complexity: O(n) — single pass through the list 🔥 Why use reduce()? Because it helps in converting a stream into a single result in a clean and functional way. Output: Microservices #Java #Java8 #Streams #Coding #Developers #Learning

To view or add a comment, sign in

Explore content categories