In this article, we will discuss how to find longest String in an Arrays and List using Java 1.8 version
1. Finding Longest String in List or ArrayList :
We will find Longest String in a List or ArrayList using different methods of Java 8 Stream
- Using Stream.max() method
- Using Stream.collect() method
- Using Stream.reduce() method
- Using Stream.sorted() method
- Using IntStream.summaryStatistics() method
- Using Collection.max() method
1.1 Using Stream.max() method
- Stream.max() method allows to get maximum value from the processing Stream elements by passing java.util.Comparator as argument
- In the below illustration we used different Comparators as method-reference to max() method,
- Comparator.comparingInt(String::length) for finding Longest String from List
- Integer::compare for finding length of Longest String
- Stream.max() method returns Optional<T>
- get() method of Optional<T> returns longest String from the List or ArrayList
- Finally, printing longest String and its length to the console
FindLongestStringInListUsingJava8StreamMaxMethod.java
package in.bench.resources.longest.string;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class FindLongestStringInListUsingJava8StreamMaxMethod {
public static void main(String[] args) {
// 1. names with different length
List<String> names = Arrays.asList(
"Bond",
"Einstein",
"Alice",
"Whitman",
"Bob",
"Spider"
);
// 1.1 print to console=
System.out.println("Original String List :- \n" + names);
// 2. find Longest name in List using max(Integer::compare).get()
String longestString = names
.stream()
.max(Comparator.comparingInt(String::length))
.get();
System.out.println("\nLongest String is = "
+ longestString);
// 2.1 find Length of Longest name in List using max(Integer::compare).get()
int lengthOflongestString = names
.stream()
.map(String::length)
.max(Integer::compare)
.get();
System.out.println("\nLength of Longest String is = "
+ lengthOflongestString);
}
}
Output:
Original String List :-
[Bond, Einstein, Alice, Whitman, Bob, Spider]
Longest String is = Einstein
Length of Longest String is = 8
1.2 Using Stream.collect() method
- Stream.collect() method accepts java.util.stream.Collectors as argument
- Collectors class has many useful methods to get maximum value from the processing Stream elements like
- Collectors.maxBy() for finding Longest String from List
- Collectors.summarizingInt() for finding length of Longest String
- Collectors.maxBy() accepts Comparator.comparingInt(String::length) as method-argument and returns Optional<T>
- get() method of Optional<T> returns longest String from the List or ArrayList
- Collectors.summarizingInt() accepts String::length as method-reference and returns IntSummaryStatistics
- getMax() method of IntSummaryStatistics returns length of the longest String from the List or ArrayList
- Finally, printing longest String and its length to the console
FindLongestStringInListUsingJava8StreamCollectMethod.java
package in.bench.resources.longest.string;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class FindLongestStringInListUsingJava8StreamCollectMethod {
public static void main(String[] args) {
// 1. names with different length
List<String> names = Arrays.asList(
"Bond",
"Einstein",
"Alice",
"Whitman",
"Bob",
"Spider"
);
// 1.1 print to console
System.out.println("Original String List :- \n" + names);
// 2. find Longest name using collect(Collectors.maxBy(Comparator.comparingInt(String::length)))
String longestStr = names
.stream()
.collect(Collectors.maxBy(Comparator.comparingInt(String::length)))
.get();
System.out.println("\nLongest String is = " + longestStr);
// 2.1 find length of Longest name using collect(Collectors.summarizingInt(String::length))
int lengthofLongestStr = names
.stream()
.collect(Collectors.summarizingInt(String::length))
.getMax();
System.out.println("\nLength of Longest String is = " + lengthofLongestStr);
}
}
Output:
Original String List :-
[Bond, Einstein, Alice, Whitman, Bob, Spider]
Longest String is = Einstein
Length of Longest String is = 8
1.3 Using Stream.reduce() method
- Stream.reduce() method accepts BinaryOperator to get maximum value from the processing Stream elements by passing lambda-expression as argument
- In the below illustration we used different lambda-expression to reduce() method,
- Lambda expression :- (x, y) -> x.length() > y.length() ? x : y for finding Longest String from List
- Lambda expression :- (x, y) -> Integer.max(x, y) for finding length of Longest String
- Stream.reduce() method returns Optional<T>
- get() method of Optional<T> returns longest String from the List or ArrayList
- Finally, printing longest String and its length to the console
FindLongestStringInListUsingJava8StreamReduceMethod.java
package in.bench.resources.longest.string;
import java.util.Arrays;
import java.util.List;
public class FindLongestStringInListUsingJava8StreamReduceMethod {
public static void main(String[] args) {
// 1. names with different length
List<String> names = Arrays.asList(
"Bond",
"Einstein",
"Alice",
"Whitman",
"Bob",
"Spider"
);
// 1.1 print to console
System.out.println("Original String List :- \n" + names);
// 2. find Longest String using .reduce((x, y) -> x.length() > y.length() ? x : y).get()
String longestStr = names
.stream()
.reduce((x, y) -> x.length() > y.length() ? x : y)
.get();
System.out.println("\nLongest String is = " + longestStr);
// 2.1 find Length of Longest String using .reduce((x, y) -> Integer.max(x, y)).getAsInt();
int lengthOfLongestStr = names
.stream()
.mapToInt(String::length)
.reduce((x, y) -> Integer.max(x, y))
.getAsInt();
System.out.println("\nLength of Longest String is = " + lengthOfLongestStr);
}
}
Output:
Original String List :-
[Bond, Einstein, Alice, Whitman, Bob, Spider]
Longest String is = Einstein
Length of Longest String is = 8
1.4 Using Stream.sorted() method
- Stream.sorted() method sorts String list on the basis of String length
- In the below illustration we are passing lambda-expression to sorted() method to sort according to String length with
- higher length String element at the top
- lower length String element at the bottom
- findFirst() method returns 1st String which has highest length in the String list and it returns Optional<T>
- get() method of Optional<T> returns longest String from the List or ArrayList
- Finally, printing longest String and its length to the console
FindLongestStringInListUsingJava8StreamSortedMethod.java
package in.bench.resources.longest.string;
import java.util.Arrays;
import java.util.List;
public class FindLongestStringInListUsingJava8StreamSortedMethod {
public static void main(String[] args) {
// 1. names with different length
List<String> names = Arrays.asList(
"Bond",
"Einstein",
"Alice",
"Whitman",
"Bob",
"Spider"
);
// 1.1 print to console
System.out.println("Original String List :- \n" + names);
// 2. find Longest name using .sorted((str1, str2) -> str1.length() > str2.length() ? -1 : 1)
String longestStr = names
.stream()
.sorted((str1, str2) -> str1.length() > str2.length() ? -1 : 1)
.findFirst()
.get();
System.out.println("\nLongest String is = " + longestStr);
// 2.1 find length of Longest name
int lengthofLongestStr = longestStr.length();
System.out.println("\nLength of Longest String is = " + lengthofLongestStr);
}
}
Output:
Original String List :-
[Bond, Einstein, Alice, Whitman, Bob, Spider]
Longest String is = Einstein
Length of Longest String is = 8
1.5 Using IntStream.summaryStatistics() method
- We can get summaryStatistics from the processing Stream elements which has useful methods to get,
- minimum value
- maximum value
- getMax() method of IntSummaryStatistics returns maximum value/element from the processing Stream elements or List or ArrayList
- Finally, printing length of longest String to the console
FindLongestStringInListUsingJava8IntSummaryStatistics.java
package in.bench.resources.longest.string;
import java.util.Arrays;
import java.util.List;
public class FindLongestStringInListUsingJava8IntSummaryStatistics {
public static void main(String[] args) {
// 1. names with different length
List<String> names = Arrays.asList(
"Bond",
"Einstein",
"Alice",
"Whitman",
"Bob",
"Spider"
);
// 1.1 print to console
System.out.println("Original String List :- " + names + "\n");
// 2. find Longest name and its length in List using .summaryStatistics().getMax()
int lengthOfLongestStr = names
.stream()
.peek(System.out::print)
.mapToInt(String::length)
.peek(length -> System.out.println("=" + length))
.summaryStatistics()
.getMax();
System.out.println("\nLength of Longest String is = " + lengthOfLongestStr);
}
}
Output:
Original String List :- [Bond, Einstein, Alice, Whitman, Bob, Spider]
Bond=4
Einstein=8
Alice=5
Whitman=7
Bob=3
Spider=6
Length of Longest String is = 8
1.6 Using Collection.max() method
- Collections.max() method accepts 2 input-arguments where
- 1st argument is the original list
- 2nd argument is the Comparator, here we are comparing on the basis of String length
- Collections.max() method returns maximum value/element according to the passed Comparator which here is String length
- Finally, printing longest String and its length to the console
FindLongestStringInListUsingJava8CollectionMaxMethod.java
package in.bench.resources.longest.string;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class FindLongestStringInListUsingJava8CollectionMaxMethod {
public static void main(String[] args) {
// 1. names with different length
List<String> names = Arrays.asList(
"Bond",
"Einstein",
"Alice",
"Whitman",
"Bob",
"Spider"
);
// 1.1 print to console=
System.out.println("Original String List :- \n" + names);
// 2. find Longest name using Collections.max()
String longestString = Collections.max(
names, // List
Comparator.comparing(String::length) // Comparator
);
System.out.println("\nLongest String is = "
+ longestString);
// 2.1 find Length of Longest name
int lengthOflongestString = longestString.length();
System.out.println("\nLength of Longest String is = "
+ lengthOflongestString);
}
}
Output:
Original String List :-
[Bond, Einstein, Alice, Whitman, Bob, Spider]
Longest String is = Einstein
Length of Longest String is = 8
2. Finding Longest number in an Arrays:
We will find Longest String in an Arrays using different methods of Java 8 Stream
- Using Arrays.stream.max() method
- Using Arrays.stream.collect() method
- Using Arrays.stream.reduce() method
- Using Arrays.stream.sorted() method
- Using IntStream.summaryStatistics() method
- Using Collection.max() method
2.1 Using Arrays.stream.max() method
- Arrays.stream.max() method returns maximum value from the processing Stream elements and this method returns Optional<T>
- get() method of Optional<T> returns longest String from the Arrays
- Finally, printing longest String and its length to the console
FindLongestStringInAnArraysUsingJava8StreamMaxMethod.java
package in.bench.resources.longest.string;
import java.util.Arrays;
import java.util.Comparator;
public class FindLongestStringInAnArraysUsingJava8StreamMaxMethod {
public static void main(String[] args) {
// 1. names with different length
String[] names = new String[] {
"Bond",
"Einstein",
"Alice",
"Whitman",
"Bob",
"Spider"
};
// 1.1 print to console
System.out.println("Original String Arrays :- \n"
+ Arrays.toString(names));
// 2. find Longest name in an Arrays using .max(Comparator.comparingInt(String::length)).get()
String longestStr = Arrays
.stream(names)
.max(Comparator.comparingInt(String::length))
.get();
System.out.println("\nLongest String is = " + longestStr);
// 2.1 find Length of Longest name in an Arrays using max(Integer::compare).get()
int lengthOflongestString = Arrays
.stream(names)
.map(String::length)
.max(Integer::compare)
.get();
System.out.println("\nLength of Longest String is = "
+ lengthOflongestString);
}
}
Output:
Original String Arrays :-
[Bond, Einstein, Alice, Whitman, Bob, Spider]
Longest String is = Einstein
Length of Longest String is = 8
2.2 Using Arrays.stream.collect() method
- Pass below arguments to Stream’s collect() method
- Collectors.maxBy() for finding Longest String from Arrays
- Collectors.summarizingInt() for finding length of Longest String
- Collectors.maxBy() accepts Comparator.comparingInt(String::length) as method-argument and returns Optional<T>
- get() method of Optional<T> returns longest String from Arrays
- Collectors.summarizingInt() accepts String::length as method-reference and returns IntSummaryStatistics
- getMax() method of IntSummaryStatistics returns length of longest String from Arrays
- Finally, printing longest String and its length to the console
FindLongestStringInAnArraysUsingJava8StreamCollectMethod.java
package in.bench.resources.longest.string;
import java.util.Arrays;
import java.util.Comparator;
import java.util.stream.Collectors;
public class FindLongestStringInAnArraysUsingJava8StreamCollectMethod {
public static void main(String[] args) {
// 1. names with different length
String[] names = new String[] {
"Bond",
"Einstein",
"Alice",
"Whitman",
"Bob",
"Spider"
};
// 1.1 print to console
System.out.println("Original String Arrays :- \n"
+ Arrays.toString(names));
// 2. find Longest name using collect(Collectors.maxBy(Comparator.comparingInt(String::length)))
String longestStr = Arrays
.stream(names)
.collect(Collectors.maxBy(Comparator.comparingInt(String::length)))
.get();
System.out.println("\nLongest String is = " + longestStr);
// 2.1 find length of Longest name using collect(Collectors.summarizingInt(String::length))
int lengthofLongestStr = Arrays
.stream(names)
.collect(Collectors.summarizingInt(String::length))
.getMax();
System.out.println("\nLength of Longest String is = " + lengthofLongestStr);
}
}
Output:
Original String Arrays :-
[Bond, Einstein, Alice, Whitman, Bob, Spider]
Longest String is = Einstein
Length of Longest String is = 8
2.3 Using Arrays.stream.reduce() method
- Arrays.stream.reduce() method accepts IntBinaryOperator to get maximum value from the processing Stream elements by passing lambda-expression as argument
- In the below illustration we used different lambda-expression to reduce() method,
- Lambda expression :- (x, y) -> x.length() > y.length() ? x : y for finding Longest String from Arrays
- Lambda expression :- (x, y) -> Integer.max(x, y) for finding length of Longest String
- Arrays.stream.reduce() method returns OptionalInt
- getAsInt() method of OptionalInt returns longest String from Arrays
- Finally, printing longest String and its length to the console
FindLongestStringInAnArraysUsingJava8StreamReduceMethod.java
package in.bench.resources.longest.string;
import java.util.Arrays;
public class FindLongestStringInAnArraysUsingJava8StreamReduceMethod {
public static void main(String[] args) {
// 1. names with different length
String[] names = new String[] {
"Bond",
"Einstein",
"Alice",
"Whitman",
"Bob",
"Spider"
};
// 1.1 print to console
System.out.println("Original String Arrays :- \n"
+ Arrays.toString(names));
// 2. find Longest String using .reduce((x, y) -> x.length() > y.length() ? x : y).get()
String longestStr = Arrays
.stream(names)
.reduce((x, y) -> x.length() > y.length() ? x : y)
.get();
System.out.println("\nLongest String is = " + longestStr);
// 2.1 find Length of Longest String using .reduce((x, y) -> Integer.max(x, y)).getAsInt();
int lengthOfLongestStr = Arrays
.stream(names)
.mapToInt(String::length)
.reduce((x, y) -> Integer.max(x, y))
.getAsInt();
System.out.println("\nLength of Longest String is = " + lengthOfLongestStr);
}
}
Output:
Original String Arrays :-
[Bond, Einstein, Alice, Whitman, Bob, Spider]
Longest String is = Einstein
Length of Longest String is = 8
2.4 Using Arrays.stream.sorted() method
- Arrays.stream.reduce() method sorts String[] Arrays on the basis of String length
- In the below illustration we are passing lambda-expression to sorted() method to sort according to String length with,
- higher length String element at the top
- lower length String element at the bottom
- findFirst() method returns 1st String which has highest length in the String[] Arrays and it returns Optional<T>
- get() method of Optional<T> returns longest String from the Arrays
- Finally, printing longest String and its length to the console
FindLongestStringInAnArraysUsingJava8StreamSortedMethod.java
package in.bench.resources.longest.string;
import java.util.Arrays;
public class FindLongestStringInAnArraysUsingJava8StreamSortedMethod {
public static void main(String[] args) {
// 1. names with different length
String[] names = new String[] {
"Bond",
"Einstein",
"Alice",
"Whitman",
"Bob",
"Spider"
};
// 1.1 print to console
System.out.println("Original String[] Arrays :- \n"
+ Arrays.toString(names));
// 2. find Longest name using .sorted((str1, str2) -> str1.length() > str2.length() ? -1 : 1)
String longestStr = Arrays
.stream(names)
.sorted((str1, str2) -> str1.length() > str2.length() ? -1 : 1)
.findFirst()
.get();
System.out.println("\nLongest String is = " + longestStr);
// 2.1 find length of Longest name
int lengthofLongestStr = longestStr.length();
System.out.println("\nLength of Longest String is = " + lengthofLongestStr);
}
}
Output:
Original String[] Arrays :-
[Bond, Einstein, Alice, Whitman, Bob, Spider]
Longest String is = Einstein
Length of Longest String is = 8
2.5 Using IntStream.summaryStatistics() method
- We can get summaryStatistics from the processing Stream elements which has useful methods to get,
- minimum value
- maximum value
- getMax() method of IntSummaryStatistics returns maximum value/element from the processing Stream elements or Arrays
- Finally, printing length of longest String to the console
FindLongestStringInAnArraysUsingJava8IntSummaryStatistics.java
package in.bench.resources.longest.string;
import java.util.Arrays;
public class FindLongestStringInAnArraysUsingJava8IntSummaryStatistics {
public static void main(String[] args) {
// 1. names with different length
String[] names = new String[] {
"Bond",
"Einstein",
"Alice",
"Whitman",
"Bob",
"Spider"
};
// 1.1 print to console
System.out.println("Original String Arrays :- \n"
+ Arrays.toString(names) + "\n");
// 2. find Longest name and its length in List using .summaryStatistics().getMax()
int lengthOfLongestStr = Arrays
.stream(names)
.peek(System.out::print)
.mapToInt(String::length)
.peek(length -> System.out.println("=" + length))
.summaryStatistics()
.getMax();
System.out.println("\nLength of Longest String is = " + lengthOfLongestStr);
}
}
Output:
Original String Arrays :-
[Bond, Einstein, Alice, Whitman, Bob, Spider]
Bond=4
Einstein=8
Alice=5
Whitman=7
Bob=3
Spider=6
Length of Longest String is = 8
2.6 Using Collection.max() method
- Collections.max() method accepts 2 input-arguments where,
- 1st argument is the list (convert original Arrays into List using Arrays.asList(); method)
- 2nd argument is the Comparator, here we are comparing on the basis of String length
- Collections.max() method returns maximum value/element according to the passed Comparator which here is String length
- Finally, printing longest String and its length to the console
FindLongestStringInAnArraysUsingJava8CollectionMaxMethod.java
package in.bench.resources.longest.string;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
public class FindLongestStringInAnArraysUsingJava8CollectionMaxMethod {
public static void main(String[] args) {
// 1. names with different length
String[] names = new String[] {
"Bond",
"Einstein",
"Alice",
"Whitman",
"Bob",
"Spider"
};
// 1.1 print to console
System.out.println("Original String[] Arrays :- \n"
+ Arrays.toString(names));
// 2. find Longest name in an Arrays using Collections.max()
String longestStr = Collections.max(
Arrays.asList(names), // Arrays converted to List
Comparator.comparing(String::length) // Comparator
);
System.out.println("\nLongest String is = " + longestStr);
// 2.1 find Length of Longest name
int lengthOflongestString = longestStr.length();
System.out.println("\nLength of Longest String is = "
+ lengthOflongestString);
}
}
Output:
Original String[] Arrays :-
[Bond, Einstein, Alice, Whitman, Bob, Spider]
Longest String is = Einstein
Length of Longest String is = 8
Related Articles:
- Java 8 – Find Largest number in an Arrays or List or Stream ?
- Java 8 – Find Smallest number in an Arrays or List or Stream ?
- Java 8 – Find 2nd Largest number in an Arrays or List or Stream ?
- Java 8 – Find 2nd Smallest number in an Arrays or List or Stream ?
- Java 8 – Find sum of Largest 2 numbers in an Arrays or List or Stream ?
- Java 8 – Find sum of Smallest 2 numbers in an Arrays or List or Stream ?
- Java 8 – Find 1st and Last elements in an Arrays ?
- Java 8 – Find 1st and Last elements in a List or ArrayList ?
- Java 8 – Find 1st and Last elements in a Set or HashSet ?
- Java 8 – Find 1st and Last entries in a Map or HashMap ?
- Java 8 – Find sum and average of a List or ArrayList ?
- Java 8 – How to calculate sum and average of an Arrays ?
References:
- https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html
- https://docs.oracle.com/javase/8/docs/api/java/util/stream/IntStream.html
- https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#max-java.util.Comparator-
- https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#collect-java.util.stream.Collector-
- https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#reduce-java.util.function.BinaryOperator-
- https://docs.oracle.com/javase/8/docs/api/java/util/IntSummaryStatistics.html
Happy Coding !!
Happy Learning !!