This is the third solution to find the maximum and minimum length strings from a given input sentence of strings, using the reduce() methods of stream.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class MinandMaxLenStrsFromGivenSentenceUsingStream {
public static void main(String args[]) {
@SuppressWarnings("resource")
Scanner inpStr = new Scanner(System.in);
System.out.print("Enter any sentence is= ");
String inpSentence = inpStr.nextLine();
System.out.println("The given sentence is=" + inpSentence);
/*
* Convert the given sentence into list of words using split, by providing one
* or more spaces regular expression
*/
ArrayList<String> arrWords = new ArrayList<>(Arrays.asList(inpSentence.split("\\s+")));
System.out.println(arrWords);
/*
* Use reduce() terminal method, and lambda expression with ternary operator, to
* find the largest string from the Arraylist of words.The final result of
* running the reducer across all elements of the array is a single value
*/
String largeString = arrWords.stream().reduce("", (s1, s2) -> s1.length() > s2.length() ? s1 : s2);
System.out.println("The largest String is=" + largeString);
/*
* reduce() method works like Identity, Accumulator, and Combiner. The reduce()
* method executes a user-supplied callback function, which acts as reducer on
* each element of the array, in the order, passing in the return value from the
* calculation on the preceding element.
*/
String smallString = arrWords.stream().reduce(inpSentence, (p1, p2) -> p1.length() < p2.length() ? p1 : p2);
System.out.println("The smallest String is=" + smallString);
}
}
OUTPUT:
Enter any sentence is= reduce method is a terminal operation results in single value
The given sentence is=reduce method is a terminal operation results in single value
[reduce, method, is, a, terminal, operation, results, in, single, value]
The largest String is=operation
The smallest String is=a

Leave a comment