Java – Find Shortest String in an Arrays or List ?

In this article, we will discuss how to find longest String in an Arrays and List using Java

1. Finding Shortest String in List or ArrayList :

We will find Shortest String in a List or ArrayList in different ways

  • Using standard for-loop in Java
  • Using enhanced for-each loop in Java 5
  • Using Java 8 Stream and Collectors
  • Using Collections.sort() method
  • Using Arrays.sort() method

1.1 Using standard for-loop in Java

  • First, assume 1st element of the list as shortest String
  • Iterate through remaining elements in the list starting with index 1 till end
    • Compare each iterating elements with assumed Shortest element
    • If iterating element is the shortest when comparing with assumed shortest element then set/assign this element as Shortest element
    • Likewise continue till the end of the loop and set/assign accordingly
  • Finally print Shortest String and its length from the List

FindShortestStringInListUsingJava.java

package in.bench.resources.shortest.string;

import java.util.Arrays;
import java.util.List;

public class FindShortestStringInListUsingJava {

	public static void main(String[] args) {

		// local variables
		String shortestStr = null;
		int lengthofShortestStr = 0;
		int indexPosition = 0;


		// 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. assume first element as Shortest
		lengthofShortestStr = names.get(0).length();


		// 2.1 Iterate and find Shortest name
		for(int index = 1; index < names.size(); index++) {

			if(names.get(index).length() < lengthofShortestStr) {
				lengthofShortestStr = names.get(index).length();
				indexPosition = index;
			}
		}


		// 2.2 get Shortest String after above iteration
		shortestStr = names.get(indexPosition);
		System.out.println("\nShortest String is " + shortestStr 
				+ " at index-position " + indexPosition);


		// 2.3 find length of Shortest name
		System.out.println("\nLength of Shortest String is = " + lengthofShortestStr);
	}
}

Output:

Original String List :- 
[Bond, Einstein, Alice, Whitman, Bob, Spider]

Shortest String is Bob at index-position 4

Length of Shortest String is = 3

1.2 Using enhanced for-each loop in Java 5

  • This illustration is very similar like previous 1.1 except that it uses enhanced for each loop introduced in Java 1.5 version
  • But code looks very elegant when comparing with previous example

FindShortestStringInListUsingJava5ForEachLoop.java

package in.bench.resources.shortest.string;

import java.util.Arrays;
import java.util.List;

public class FindShortestStringInListUsingJava5ForEachLoop {

	public static void main(String[] args) {

		// local variables
		String shortestStr = null;


		// 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. iterate using Java 5 and find Shortest String
		for(String name : names) {
			if(null == shortestStr || name.length() < shortestStr.length()) {
				shortestStr = name;
			}
		}


		// 2.1 print Shortest String after above iteration
		System.out.println("\nShortest String is = " + shortestStr);


		// 2.2 find length of Shortest name
		System.out.println("\nLength of Shortest String is = " + shortestStr.length());
	}
}

Output:

Original String List :- 
[Bond, Einstein, Alice, Whitman, Bob, Spider]

Shortest String is = Bob

Length of Shortest String is = 3

1.3 Using Java 8 Stream and Collectors

1.4 Using Collections.sort() method

  • Collections.sort() method accepts 2 input-arguments where,
    • 1st argument is the actual String list from which shortest String has to be find
    • 2nd argument is the Comparator for sorting which here is according to String length
  • Get the first element using index-position which gives shortest String after sorting
  • Finally print Shortest String and its length from the List

FindShortestStringInListUsingCollectionSortingByLength.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 FindShortestStringInListUsingCollectionSortingByLength {

	public static void main(String[] args) {

		// local variables
		String shortestStr = null;


		// 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. sort List according to String length
		Collections.sort(names, new Comparator<String>() {

			@Override
			public int compare(String str1, String str2) {
				return str1.length() - str2.length();
			}
		});


		// 2.1 get Shortest String after above sorting
		shortestStr = names.get(0);
		System.out.println("\nShortest String is = " + shortestStr);


		// 2.2 find length of Shortest name
		System.out.println("\nLength of Shortest String is = " + shortestStr.length());
	}
}

Output:

Original String List :- 
[Bond, Einstein, Alice, Whitman, Bob, Spider]

Shortest String is = Bob

Length of Shortest String is = 3

1.5 Using Arrays.sort() method

  • Arrays.sort() method accepts 2 input-arguments where,
    • 1st argument is the arrays from which shortest String has to be find (convert actual String list to Arrays using list.toArray(new String[0]); method)
    • 2nd argument is the Comparator for sorting which here is according to String length
  • Get the first element using index-position which gives shortest String after sorting
  • Finally print Shortest String and its length from the List

FindShortestStringInListUsingArraysSortingByLength.java

package in.bench.resources.shortest.string;

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

public class FindShortestStringInListUsingArraysSortingByLength {

	public static void main(String[] args) {

		// local variables
		String shortestStr = null;


		// 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. convert List to Arrays
		String[] sortedArrays = names.toArray(new String[0]);


		// 2.1 sort converted Arrays according to String length
		Arrays.sort(sortedArrays, new Comparator<String>() {

			@Override
			public int compare(String str1, String str2) {
				return str1.length() - str2.length();
			}
		});


		// 2.2 get Shortest String after above sorting
		shortestStr = sortedArrays[0];
		System.out.println("\nShortest String is = " + shortestStr);


		// 2.3 find length of Shortest name
		System.out.println("\nLength of Shortest String is = " + shortestStr.length());
	}
}

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 in different ways

  • Using standard for-loop in Java
  • Using enhanced for-each loop in Java 5
  • Using Java 8 Stream and Collectors
  • Using Arrays.sort() method
  • Using Collections.sort() method

2.1 Using standard for-loop in Java

  • First, assume 1st element of the Arrays as shortest String
  • Iterate through remaining elements in the Arrays starting with index 1 till end
    • Compare each iterating elements with assumed Shortest element
    • If iterating element is the shortest when comparing with assumed shortest element then set/assign this element as Shortest element
    • Likewise continue till the end of the loop and set/assign accordingly
  • Finally print Shortest String and its length from Arrays

FindShortestStringInAnArraysUsingJava.java

package in.bench.resources.shortest.string;

import java.util.Arrays;

public class FindShortestStringInAnArraysUsingJava {

	public static void main(String[] args) {

		// local variables
		String shortestStr = null;
		int lengthofShortestStr = 0;
		int indexPosition = 0;


		// 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. assume first element as Shortest
		lengthofShortestStr = names[0].length();


		// 2.1 Iterate and find Shortest name
		for(int index = 1; index < names.length; index++) {

			if(names[index].length() < lengthofShortestStr) {
				lengthofShortestStr = names[index].length();
				indexPosition = index;
			}
		}


		// 2.2 get Shortest String after above iteration
		shortestStr = names[indexPosition];
		System.out.println("\nShortest String is " + shortestStr 
				+ " at index-position " + indexPosition);


		// 2.3 find length of Shortest name
		System.out.println("\nLength of Shortest String is = " + lengthofShortestStr);
	}
}

Output:

Original String[] Arrays :- 
[Bond, Einstein, Alice, Whitman, Bob, Spider]

Shortest String is Bob at index-position 4

Length of Shortest String is = 3



2.2 Using enhanced for-each loop in Java 5

  • This illustration is very similar like previous 2.1 except that it uses enhanced for each loop introduced in Java 1.5 version
  • But code looks very elegant when comparing with previous example

FindShortestStringInAnArraysUsingJava5ForEach.java

package in.bench.resources.shortest.string;

import java.util.Arrays;

public class FindShortestStringInAnArraysUsingJava5ForEach {

	public static void main(String[] args) {

		// local variables
		String shortestStr = null;


		// 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. iterate using Java 5 and find Shortest String
		for(String name : names) {
			if(null == shortestStr || name.length() < shortestStr.length()) {
				shortestStr = name;
			}
		}


		// 2.1 print Shortest String after above iteration
		System.out.println("\nShortest String is = " + shortestStr);


		// 2.2 find length of Shortest name
		System.out.println("\nLength of Shortest String is = " + shortestStr.length());
	}
}

Output:

Original String[] Arrays :- 
[Bond, Einstein, Alice, Whitman, Bob, Spider]

Shortest String is = Bob

Length of Shortest String is = 3



2.3 Using Java 8 Stream and Collectors

  • With Java 1.8 version we can find Shortest String using Stream methods like
    • Arrays.stream.min() method
    • Arrays.stream.reduce() method
    • Arrays.stream.collect() method
    • Arrays.stream.sorted() method
    • IntStream.summaryStatistics() method
    • Collections.min() method
  • Read Java 8 – Find Shortest String in an Arrays or List or Stream ?



2.4 Using Arrays.sort() method

  • Arrays.sort() method accepts 2 input-arguments where,
    • 1st argument is the arrays from which shortest String has to be find
    • 2nd argument is the Comparator for sorting which here is according to String length
  • Get the first element using index-position which gives shortest String after sorting
  • Finally print Shortest String and its length from Arrays

FindShortestStringInAnArraysUsingArraysSortingByLength.java

package in.bench.resources.shortest.string;

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

public class FindShortestStringInAnArraysUsingArraysSortingByLength {

	public static void main(String[] args) {

		// local variables
		String shortestStr = null;


		// 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. sort converted Arrays according to String length
		Arrays.sort(names, new Comparator<String>() {

			@Override
			public int compare(String str1, String str2) {
				return str1.length() - str2.length();
			}
		});


		// 2.2 get Shortest String after above sorting
		shortestStr = names[0];
		System.out.println("\nShortest String is = " + shortestStr);


		// 2.3 find length of Shortest name
		System.out.println("\nLength of Shortest String is = " + shortestStr.length());
	}
}

Output:

Original String[] Arrays :- 
[Bond, Einstein, Alice, Whitman, Bob, Spider]

Shortest String is = Bob

Length of Shortest String is = 3

2.5 Using Collections.sort() method

  • Collections.sort() method accepts 2 input-arguments where,
    • 1st argument is the list from which shortest String has to be find (convert Arrays into List using Arrays.asList(); method)
    • 2nd argument is the Comparator for sorting which here is according to String length
  • Get the first element using index-position which gives shortest String after sorting
  • Finally print Shortest String and its length from Arrays

FindShortestStringInAnArraysUsingCollectionSortingByLength.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 FindShortestStringInAnArraysUsingCollectionSortingByLength {

	public static void main(String[] args) {

		// local variables
		String shortestStr = null;


		// 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. convert to List
		List<String> sortedNames = Arrays.asList(names);


		// 2.1 sort List according to String length
		Collections.sort(sortedNames, new Comparator<String>() {

			@Override
			public int compare(String str1, String str2) {
				return str1.length() - str2.length();
			}
		});


		// 2.2 get Shortest String after above sorting
		shortestStr = sortedNames.get(0);
		System.out.println("\nShortest String is = " + shortestStr);


		// 2.3 find length of Shortest name
		System.out.println("\nLength of Shortest String is = " + shortestStr.length());
	}
}

Output:

Original String[] Arrays :- 
[Bond, Einstein, Alice, Whitman, Bob, Spider]

Shortest String is = Bob

Length of Shortest String is = 3

Related Articles:

Happy Coding !!
Happy Learning !!

Java 8 – Find Third Longest String in an Arrays or List or Stream ?
Java – Find Longest String in an Arrays or List ?