OneCompiler

[Java] How to get longest string from an array?

I want to find the longest string (in terms of length) from an array, How can I do that in Java?

1 Answer

4 years ago by

We can use max on a Stream to find the longest string from Array, following code shows how to do that.

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

public class JavaArrays {
	public static void main(String[] args) {
		String[] array = { "a", "b", "c", "d", "aaa", "ab" };

		String result = Arrays.stream(array)
								.max(Comparator.comparingInt(String::length))
								.get();

		System.out.println(result);
	}
}

Outout:

aaa

Try this code online here: https://onecompiler.com/java/3xmt8dcdx

4 years ago by Karthik Divi