In this article, we will discuss how to find shortest String in an Arrays and List using Java 1.8 version
1. Finding Shortest String in List or ArrayList :
We will find Shortest String in a List or ArrayList using different methods of Java 8 Stream
- Using Stream.min() method
- Using Stream.collect() method
- Using Stream.reduce() method
- Using Stream.sorted() method
- Using IntStream.summaryStatistics() method
- Using Collection.min() method
1.1 Using Stream.min() method
- Stream.min() method allows to get minimum 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 min() method,
- Comparator.comparingInt(String::length) for finding Shortest String from List
- Integer::compare for finding length of Shortest String
- Stream.min() method returns Optional<T>
- get() method of Optional<T> returns shortest String from the List or ArrayList
- Finally, printing shortest String and its length to the console
FindShortestStringInListUsingJava8StreamMinMethod.java
package in.bench.resources.shortest.string;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class FindShortestStringInListUsingJava8StreamMinMethod {
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 Shortest String using .min(Comparator.comparingInt(String::length)).get()
String shortestString = names
.stream()
.min(Comparator.comparingInt(String::length))
.get();
System.out.println("\nShortest String is = "
+ shortestString);
// 2.1 find Length of Shortest String using min(Integer::compare).get()
int lengthOfShortestString = names
.stream()
.map(String::length)
.min(Integer::compare)
.get();
System.out.println("\nLength of Shortest String is = "
+ lengthOfShortestString);
}
}
Output:
Original String List :-
[Bond, Einstein, Alice, Whitman, Bob, Spider]
Shortest String is = Bob
Length of Shortest String is = 3
1.2 Using Stream.collect() method
- Stream.collect() method accepts java.util.stream.Collectors as argument
- Collectors class has many useful methods to get minimum value from the processing Stream elements like
- Collectors.minBy() for finding Shortest String from List
- Collectors.summarizingInt() for finding length of Shortest String
- Collectors.minBy() accepts Comparator.comparingInt(String::length) as method-argument and returns Optional<T>
- get() method of Optional<T> returns shortest String from the List or ArrayList
- Collectors.summarizingInt() accepts String::length as method-reference and returns IntSummaryStatistics
- getMin() method of IntSummaryStatistics returns length of the shortest String from the List or ArrayList
- Finally, printing shortest String and its length to the console
FindShortestStringInListUsingJava8StreamCollectMethod.java
package in.bench.resources.shortest.string;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class FindShortestStringInListUsingJava8StreamCollectMethod {
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 Shortest name using .collect(Collectors.minBy(Comparator.comparingInt(String::length)))
String shortestStr = names
.stream()
.collect(Collectors.minBy(Comparator.comparingInt(String::length)))
.get();
System.out.println("\nShortest String is = " + shortestStr);
// 2.1 find length of Shortest String using .collect(Collectors.summarizingInt(String::length))
int lengthofShortestStr = names
.stream()
.collect(Collectors.summarizingInt(String::length))
.getMin();
System.out.println("\nLength of Shortest String is = " + lengthofShortestStr);
}
}
Output:
Original String List :-
[Bond, Einstein, Alice, Whitman, Bob, Spider]
Shortest String is = Bob
Length of Shortest String is = 3
1.3 Using Stream.reduce() method
- Stream.reduce() method accepts BinaryOperator to get minimum 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 Shortest String from List
- Lambda expression :- (x, y) -> Integer.min(x, y) for finding length of Shortest String
- Stream.reduce() method returns Optional<T>
- get() method of Optional<T> returns shortest String from the List or ArrayList
- Finally, printing shortest String and its length to the console
FindShortestStringInListUsingJava8StreamReduceMethod.java
package in.bench.resources.shortest.string;
import java.util.Arrays;
import java.util.List;
public class FindShortestStringInListUsingJava8StreamReduceMethod {
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 Shortest String using .reduce((x, y) -> x.length() < y.length() ? x : y).get()
String shortestStr = names
.stream()
.reduce((x, y) -> x.length() < y.length() ? x : y)
.get();
System.out.println("\nShortest String is = " + shortestStr);
// 2.1 find Length of Shortest String using .reduce((x, y) -> Integer.min(x, y)).getAsInt();
int lengthOfShortestStr = names
.stream()
.mapToInt(String::length)
.reduce((x, y) -> Integer.min(x, y))
.getAsInt();
System.out.println("\nLength of Shortest String is = " + lengthOfShortestStr);
}
}
Output:
Original String List :-
[Bond, Einstein, Alice, Whitman, Bob, Spider]
Shortest String is = Bob
Length of Shortest String is = 3
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
- lower length String element at the top
- higher length String element at the bottom
- findFirst() method returns 1st String which has lowest length in the String list and its returns Optional<T>
- get() method of Optional<T> returns shortest String from the List or ArrayList
- Finally, printing shortest String and its length to the console
FindShortestStringInListUsingJava8StreamSortedMethod.java
package in.bench.resources.shortest.string;
import java.util.Arrays;
import java.util.List;
public class FindShortestStringInListUsingJava8StreamSortedMethod {
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 Shortest name using .sorted((str1, str2) -> str1.length() < str2.length() ? -1 : 1)
String shortestStr = names
.stream()
.sorted((str1, str2) -> str1.length() < str2.length() ? -1 : 1)
.findFirst()
.get();
System.out.println("\nShortest String is = " + shortestStr);
// 2.1 find length of Shortest String
int lengthofShortestStr = shortestStr.length();
System.out.println("\nLength of Shortest String is = " + lengthofShortestStr);
}
}
Output:
Original String List :-
[Bond, Einstein, Alice, Whitman, Bob, Spider]
Shortest String is = Bob
Length of Shortest String is = 3
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
- getMin() method of IntSummaryStatistics returns minimum value/element from the processing Stream elements or List or ArrayList
- Finally, printing length of shortest String to the console
FindShortestStringInListUsingJava8IntSummaryStatistics.java
package in.bench.resources.shortest.string;
import java.util.Arrays;
import java.util.List;
public class FindShortestStringInListUsingJava8IntSummaryStatistics {
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 Shortest name and its length using .summaryStatistics().getMin()
int lengthOfShortestStr = names
.stream()
.peek(System.out::print)
.mapToInt(String::length)
.peek(length -> System.out.println("=" + length))
.summaryStatistics()
.getMin();
System.out.println("\nLength of Shortest String is = " + lengthOfShortestStr);
}
}
Output:
Original String List :- [Bond, Einstein, Alice, Whitman, Bob, Spider]
Bond=4
Einstein=8
Alice=5
Whitman=7
Bob=3
Spider=6
Length of Shortest String is = 3
1.6 Using Collection.min() method
- Collections.min() 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.min() method returns minimum value/element according to the passed Comparator which here is String length
- Finally, printing shortest String and its length to the console
FindShortestStringInListUsingJava8CollectionMinMethod.java
package in.bench.resources.shortest.string;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class FindShortestStringInListUsingJava8CollectionMinMethod {
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 Shortest name using Collections.min()
String shortestString = Collections.min(
names, // List
Comparator.comparing(String::length) // Comparator
);
System.out.println("\nShortest String is = "
+ shortestString);
// 2.1 find Length of Shortest name
int lengthOfShortestString = shortestString.length();
System.out.println("\nLength of Shortest String is = "
+ lengthOfShortestString);
}
}
Output:
Original String List :-
[Bond, Einstein, Alice, Whitman, Bob, Spider]
Shortest String is = Bob
Length of Shortest String is = 3
2. Finding Shortest String in an Arrays:
We will find Shortest String in an Arrays using different methods of Java 8 Stream
- Using Arrays.stream.min() method
- Using Arrays.stream.collect() method
- Using Arrays.stream.reduce() method
- Using Arrays.stream.sorted() method
- Using IntStream.summaryStatistics() method
- Using Collection.min() method
2.1 Using Arrays.stream.min() method
- Arrays.stream.min() method returns minimum value from the processing Stream elements and this method returns Optional<T>
- get() method of Optional<T> returns shortest String from the Arrays
- Finally, printing shortest String and its length to the console
FindShortestStringInAnArraysUsingJava8StreamMinMethod.java
package in.bench.resources.shortest.string;
import java.util.Arrays;
import java.util.Comparator;
public class FindShortestStringInAnArraysUsingJava8StreamMinMethod {
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 Shortest String using .min(Comparator.comparingInt(String::length)).get()
String shortestStr = Arrays
.stream(names)
.min(Comparator.comparingInt(String::length))
.get();
System.out.println("\nShortest String is = " + shortestStr);
// 2.1 find Length of Shortest String using .min(Integer::compare).get()
int lengthOfShortestString = Arrays
.stream(names)
.map(String::length)
.min(Integer::compare)
.get();
System.out.println("\nLength of Shortest String is = "
+ lengthOfShortestString);
}
}
Output:
Original String[] Arrays :-
[Bond, Einstein, Alice, Whitman, Bob, Spider]
Shortest String is = Bob
Length of Shortest String is = 3
2.2 Using Arrays.stream.collect() method
- Pass below arguments to Stream’s collect() method
- Collectors.minBy() for finding Shortest String from Arrays
- Collectors.summarizingInt() for finding length of Shortest String
- Collectors.minBy() accepts Comparator.comparingInt(String::length) as method-argument and returns Optional<T>
- get() method of Optional<T> returns shortest String from Arrays
- Collectors.summarizingInt() accepts String::length as method-reference and returns IntSummaryStatistics
- getMin() method of IntSummaryStatistics returns length of shortest String from Arrays
- Finally, printing shortest String and its length to the console
FindShortestStringInAnArraysUsingJava8StreamCollectMethod.java
package in.bench.resources.shortest.string;
import java.util.Arrays;
import java.util.Comparator;
import java.util.stream.Collectors;
public class FindShortestStringInAnArraysUsingJava8StreamCollectMethod {
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 Shortest String using collect(Collectors.minBy(Comparator.comparingInt(String::length))
String shortestStr = Arrays
.stream(names)
.collect(Collectors.minBy(Comparator.comparingInt(String::length)))
.get();
System.out.println("\nShortest String is = " + shortestStr);
// 2.1 find length of Shortest String using .collect(Collectors.summarizingInt(String::length))
int lengthofShortestStr = Arrays
.stream(names)
.collect(Collectors.summarizingInt(String::length))
.getMin();
System.out.println("\nLength of Shortest String is = " + lengthofShortestStr);
}
}
Output:
Original String[] Arrays :-
[Bond, Einstein, Alice, Whitman, Bob, Spider]
Shortest String is = Bob
Length of Shortest String is = 3
2.3 Using Arrays.stream.reduce() method
- Arrays.stream.reduce() method accepts IntBinaryOperator to get minimum 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 Shortest String from Arrays
- Lambda expression :- (x, y) -> Integer.min(x, y) for finding length of Shortest String
- Arrays.stream.reduce() method returns OptionalInt
- getAsInt() method of OptionalInt returns shortest String from Arrays
- Finally, printing shortest String and its length to the console
FindShortestStringInAnArraysUsingJava8StreamReduceMethod.java
package in.bench.resources.shortest.string;
import java.util.Arrays;
public class FindShortestStringInAnArraysUsingJava8StreamReduceMethod {
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 Shortest String using .reduce((x, y) -> x.length() < y.length() ? x : y).get()
String shortestStr = Arrays
.stream(names)
.reduce((x, y) -> x.length() < y.length() ? x : y)
.get();
System.out.println("\nShortest String is = " + shortestStr);
// 2.1 find Length of Shortest String using .reduce((x, y) -> Integer.min(x, y)).getAsInt()
int lengthOfShortestStr = Arrays
.stream(names)
.mapToInt(String::length)
.reduce((x, y) -> Integer.min(x, y))
.getAsInt();
System.out.println("\nLength of Shortest String is = " + lengthOfShortestStr);
}
}
Output:
Original String[] Arrays :-
[Bond, Einstein, Alice, Whitman, Bob, Spider]
Shortest String is = Bob
Length of Shortest String is = 3
2.4 Using Arrays.stream.sorted() method
- Stream.sorted() 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
- lower length String element at the top
- higher length String element at the bottom
- findFirst() method returns 1st String which has lowest length in the String[] Arrays and it returns Optional<T>
- get() method of Optional<T> returns shortest String from the Arrays
- Finally, printing shortest String and its length to the console
FindShortestStringInAnArraysUsingJava8StreamSortedMethod.java
package in.bench.resources.shortest.string;
import java.util.Arrays;
public class FindShortestStringInAnArraysUsingJava8StreamSortedMethod {
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 Shortest String using .sorted((str1, str2) -> str1.length() < str2.length() ? -1 : 1)
String shortestStr = Arrays
.stream(names)
.sorted((str1, str2) -> str1.length() < str2.length() ? -1 : 1)
.findFirst()
.get();
System.out.println("\nShortest String is = " + shortestStr);
// 2.1 find length of Shortest String
int lengthofShortestStr = shortestStr.length();
System.out.println("\nLength of Shortest String is = " + lengthofShortestStr);
}
}
Output:
Original String[] Arrays :-
[Bond, Einstein, Alice, Whitman, Bob, Spider]
Shortest String is = Bob
Length of Shortest String is = 3
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
- getMin() method of IntSummaryStatistics returns minimum value/element from the processing Stream elements or Arrays
- Finally, printing length of shortest String to the console
FindShortestStringInAnArraysUsingJava8IntSummaryStatistics.java
package in.bench.resources.shortest.string;
import java.util.Arrays;
public class FindShortestStringInAnArraysUsingJava8IntSummaryStatistics {
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 Shortest String and its length using .summaryStatistics().getMin()
int lengthOfShortestStr = Arrays
.stream(names)
.peek(System.out::print)
.mapToInt(String::length)
.peek(length -> System.out.println("=" + length))
.summaryStatistics()
.getMin();
System.out.println("\nLength of Shortest String is = " + lengthOfShortestStr);
}
}
Output:
Original String[] Arrays :-
[Bond, Einstein, Alice, Whitman, Bob, Spider]
Bond=4
Einstein=8
Alice=5
Whitman=7
Bob=3
Spider=6
Length of Shortest String is = 3
2.6 Using Collection.min() method
- Collections.min() 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.min() method returns minimum value/element according to the passed Comparator which here is String length
- Finally, printing shortest String and its length to the console
FindShortestStringInAnArraysUsingJava8CollectionMinMethod.java
package in.bench.resources.shortest.string;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
public class FindShortestStringInAnArraysUsingJava8CollectionMinMethod {
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 Shortest name in an Arrays using Collections.min()
String shortestStr = Collections.min(
Arrays.asList(names), // Arrays converted to List
Comparator.comparing(String::length) // Comparator
);
System.out.println("\nShortest String is = " + shortestStr);
// 2.1 find Length of Shortest name
int lengthOfShortestString = shortestStr.length();
System.out.println("\nLength of Shortest String is = "
+ lengthOfShortestString);
}
}
Output:
Original String[] Arrays :-
[Bond, Einstein, Alice, Whitman, Bob, Spider]
Shortest String is = Bob
Length of Shortest String is = 3
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 !!