To find the longest string in a list in Java, you can use the stream()
method to create a stream of the list, and then use the max()
method to find the maximum value based on the length of the strings.
Here's an example of how to do it:
import java.util.Arrays; import java.util.List; import java.util.Optional; public class Main { public static void main(String[] args) { List<String> list = Arrays.asList("apple", "banana", "cherry", "date", "elderberry", "fig"); // Find the longest string in the list Optional<String> longest = list.stream() .max((s1, s2) -> s1.length() - s2.length()); if (longest.isPresent()) { System.out.println(longest.get()); // prints "elderberry" } } }
This code creates a list of strings and then uses the max()
method to find the maximum value based on the length of the strings. The isPresent()
method is used to check if a maximum value was found, and the get()
method is used to retrieve the value.