Member-only story

How to find longest string in an array of strings.

--

In this tutorial, we will learn how to find longest string from array of strings using java 8 stream API.

package com.demo.main;

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

public class FineLongestStringFromArray {

public static void main(String[] args) {

String[] names = {"sumit", "karan", "GainJavaKnowledge", "Vivek", "MontyNewMemeberOnThisGroup"};

// String longetsString = Arrays.stream(names).max(Comparator.comparingInt(String::length)).get();

String longetsString = Arrays.stream(names).reduce((x,y)-> x.length() > y.length()? x : y).get();
System.out.println("Longest String : "+longetsString);

}
}

In the above code, we have used reduce() function of java8 using that we can find longest string from an array after comparison of each string. Stream.reduce() method accepts BinaryOperator to get maximum value from the processing stream elements by passing lambda expression as argument. (x,y)-> x.length() > y.length()? x : y for finding longest string from list.

Watch Video Here :

--

--

Gain Java Knowledge
Gain Java Knowledge

Written by Gain Java Knowledge

The Java programming language is one of the most popular languages today. Stay up to date with news, certifications, free learning resources and much more.

No responses yet