Find Longest String in Java 8 Using Stream max() Method

Learn how to find longest string in Java 8 using Stream max() Method ,Arrays.asList(), Stream API and lambda expression with a simple example.

Code Explanation (Step-by-Step)

  • Arrays.asList() converts the given string values into a List<String>.
  • The stream() method converts the list into a stream .
  • max() is used to find the maximum element from the Stream based on a specified comparison condition.
  • The lambda expression (s1, s2) -> s1.length() – s2.length() compares the lengths of two strings .
  • During comparison:
    • A positive value indicates s1 is longer than s2.
    • A negative value indicates s2 is longer than s1.
    • Zero indicates both strings have the same length.
  • The max() method continuously compares all strings and identifies the string with the greatest length.
  • max() returns the result as an Optional<String> object.
  • get() extracts the longest string from the Optional object.
  • Now prints the longest string on the console.
				
					import java.util.Arrays;
import java.util.List;

public class LongestString {
	public static void main(String[] args) {
		List<String> list = Arrays.asList("java", "hibernate", "spring", "servlet");
		
		String longest = list.stream()
		                 .max((s1, s2) -> s1.length() - s2.length())
		                .get();
		System.out.println("Longest string is :- " + longest);
	}
}
				
			

Output :
Longest string is :- hibernate

Find the Longest String in a List in Java 8 Using Comparator.comparingInt()

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

public class LongestStringExample {
    public static void main(String[] args) {

        List<String> list = Arrays.asList("java", "hibernate", "spring", "servlet");

        String longest = list.stream()
                .max(Comparator.comparingInt(String::length))
                .get();

        System.out.println("Longest String is: " + longest);
    }
}
				
			

Output :
Longest string is :- hibernate

FAQ :
What is the best way to find the longest string in Java 8?
The best way is to use Java 8 Stream API with the max() method and a comparator that compares the length of strings.
Which Java 8 method is used to find the shortest string from a list?
The Stream.min() method is used to find the longest string from a list by comparing string lengths.
What does max() return in Java Stream API?
The max() method returns an Optional<T> because the stream may be empty.
Can we find the longest string from an array without converting it into a List?
Yes, we can directly use Arrays.stream(array) to create a stream from the array and then apply the max() method.