Java – Find Third Shortest String in an Arrays or List ?

In this article, we will discuss how to find third shortest String in an Arrays and List

1. Finding Third Shortest String in an Arrays:

We will follow below 2 approaches to get 3rd Shortest String in an Arrays

  • Using SortedSet and TreeSet
  • Using Arrays sorting

1.1 Using SortedSet & TreeSet approach

  • Create TreeSet object with SortedSet reference and pass Comparator as constructor-argument for String length comparison
  • Now, elements inside TreeSet object will be sorted according to String length and first element will be the shortest element
  • Using first() method of SortedSet reference, we can get first element and that will be the shortest element
  • Remove first 2 elements using remove() method of SortedSet reference passing sortedSet.first() method as argument
  • Now after removing first 2 elements, current first element in the TreeSet object will be the 3rd shortest String
  • Finally print 3rd shortest String to the console

FindThirdShortestStringInAnArraysUsingTreeSet.java

package in.bench.resources.third.shortest.string;

import java.time.Duration;
import java.time.LocalTime;
import java.util.Arrays;
import java.util.Comparator;
import java.util.SortedSet;
import java.util.TreeSet;

public class FindThirdShortestStringInAnArraysUsingTreeSet {

	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. Execution - start time
		LocalTime startTime = LocalTime.now();


		// 2.1 create an Object of TreeSet which stores elements 
		SortedSet<String> sortedSet = new TreeSet<String>(
				new Comparator<String>() {

					@Override
					public int compare(String str1, String str2) {
						return str1.length() - str2.length();// acc. to String length in ASC order
					}
				});


		// 2.2 convert Arrays to List and addAll to above Set
		sortedSet.addAll(Arrays.asList(names));


		// 2.3 remove first 2 elements
		sortedSet.remove(sortedSet.first()); // shortest
		sortedSet.remove(sortedSet.first()); // second shortest


		// 2.4 now, this will be Third shortest String
		String thirdShortestString = sortedSet.first();


		// 2.5 Execution - end time
		LocalTime endTime = LocalTime.now();


		// 2.6 find difference
		Duration duration = Duration.between(startTime, endTime);
		long differenceInNano = duration.getNano();


		// 2.7 print to console
		System.out.println("\nThird Shortest String in an Arrays is - "
				+ thirdShortestString);


		// 2.8 print execution time in nanoseconds
		System.out.println("\nExecution time - "
				+ differenceInNano + " ns");
	}
}

Output:

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

Third Shortest String in an Arrays is - Alice

Execution time - 1012500 ns

1.2 Using Arrays sorting approach

  • First step is to sort String[] Arrays using Arrays.sort() method in ascending-order
  • Arrays.sort() method accepts 2 input-arguments
    • 1st argument is the actual Arrays to be sorted
    • 2nd argument is the anonymous Comparator object with logic for ascending-order sorting of String[] Arrays
  • After sorting, get 3rd shortest String by passing index of third element to String[] Arrays

FindThirdShortestStringInAnArraysUsingSortMethod.java

package in.bench.resources.third.shortest.string;

import java.time.Duration;
import java.time.LocalTime;
import java.util.Arrays;
import java.util.Comparator;

public class FindThirdShortestStringInAnArraysUsingSortMethod {

	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. Execution - start time
		LocalTime startTime = LocalTime.now();


		// 2.1 sort Arrays element in ascending order of String length
		Arrays.sort(
				names, // original Arrays
				new Comparator<String>() {

					@Override
					public int compare(String str1, String str2) {
						return str1.length() - str2.length();// acc. to String length in ASC order
					}
				});


		// 2.2 get 3rd element after sorting
		String thirdShortestString = names[2];


		// 2.3 Execution - end time
		LocalTime endTime = LocalTime.now();


		// 2.4 find difference
		Duration duration = Duration.between(startTime, endTime);
		long differenceInNano = duration.getNano();


		// 2.5 print to console
		System.out.println("\nThird shortest String in an Arrays is - "
				+ thirdShortestString);


		// 2.6 print execution time in nanoseconds
		System.out.println("\nExecution time - "
				+ differenceInNano + " ns");
	}
}

Output:

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

Third shortest String in an Arrays is - Alice

Execution time - 955800 ns

2. Finding Third shortest String in List:

  • First step is to sort List of String using Collections.sort() method in ascending-order
  • Collections.sort() method accepts 2 input-arguments
    • 1st argument is the actual List to be sorted
    • 2nd argument is the anonymous Comparator object with logic for ascending-order sorting of String[] Arrays
  • After sorting, get 3rd shortest String by passing index of third element to String List

FindThirdShortestStringInListUsingCollectionsSortMethod.java

package in.bench.resources.third.shortest.string;

import java.time.Duration;
import java.time.LocalTime;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class FindThirdShortestStringInListUsingCollectionsSortMethod {

	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. Execution - start time
		LocalTime startTime = LocalTime.now();


		// 2.1 sort List element in ascending order
		Collections.sort(
				names, // original List
				new Comparator<String>() {

					@Override
					public int compare(String str1, String str2) {
						return str1.length() - str2.length();// acc. to String length in ASC order
					}
				});


		// 2.2 get 3rd element after sorting
		String thirdShortestString = names.get(2);


		// 2.4 Execution - end time
		LocalTime endTime = LocalTime.now();


		// 2.5 find difference
		Duration duration = Duration.between(startTime, endTime);
		long differenceInNano = duration.getNano();


		// 2.6 print to console
		System.out.println("\nThird shortest String in List is - "
				+ thirdShortestString);


		// 2.7 print execution time in nanoseconds
		System.out.println("\nExecution time - "
				+ differenceInNano + " ns");
	}
}

Output:

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

Third shortest String in List is - Alice

Execution time - 1000100 ns

3. Points to remember w.r.t execution time:

  • Execution time differs in different platforms
  • With small set of numbers, we may not find large difference in execution time
  • But with large set of numbers, difference will be significant to consider

Related Articles:

Happy Coding !!
Happy Learning !!

Java – Find all longest Strings in List or Arrays ?
Java – Find Third Longest String in an Arrays or List ?