Java – How to Sort String[] Arrays by its length ?

In this article, we will discuss how to sort String[] Arrays by its length in Ascending-order and Descending-order

Sorting String[] Arrays by its length:

  1. Using TreeSet (inter-conversion constructor)
  2. Using Arrays.sort() method

1. Using TreeSet :

  • There is a String[] Arrays with different length in random-order which needs to be sorted according to String length
  • Ascending-order sorting :
    • Create TreeSet passing Comparator as constructor-argument with ascending-order of String length logic
    • Add original String[] Arrays elements to newly created TreeSet using addAll() method after converting String[] Arrays into List
  • Descending-order sorting :
    • Create TreeSet passing Comparator as constructor-argument with descending-order of String length logic
    • Add original String[] Arrays elements to newly created TreeSet using addAll() method after converting String[] Arrays into List
  • Print TreeSet object to the console for both ascending-order and descending-order of String[] Arrays in accordance with its String length
  • Note: If there are multiple Strings of same length in the String[] Arrays then this will discard elements of same length as Set doesn’t allows duplicates
  • Check below example 2 if there are multiple Strings of same length

SortingStringArraysByItsLengthUsingTreeSet.java

package in.bench.resources.sorting.string.arrays;

import java.util.Arrays;
import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;

public class SortingStringArraysByItsLengthUsingTreeSet {

	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. sorting String[] Arrays in Ascending-order
		Set<String> treeSetAsc = new TreeSet<>(new Comparator<String>() {

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


		// 2.1 add String[] Arrays items to TreeSet
		treeSetAsc.addAll(Arrays.asList(names));


		// 2.2 print ascending-order sorted Strings by its Length
		System.out.println("\nAscending-order Sorted String[] Arrays by its Length :- \n" 
				+ treeSetAsc + "\n");



		// 3. sorting String[] Arrays in Descending-order
		Set<String> treeSetDesc = new TreeSet<>(new Comparator<String>() {

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


		// 3.1 add String[] Arrays items to TreeSet
		treeSetDesc.addAll(Arrays.asList(names));


		// 3.2 print descending-order sorted Strings by its Length
		System.out.print("\nDescending-order Sorted String[] Arrays by its Length :- \n" 
				+ treeSetDesc);
	}
}

Output:

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


Ascending-order Sorted String[] Arrays by its Length :- 
[Bob, Bond, Alice, Spider, Whitman, Einstein]


Descending-order Sorted String[] Arrays by its Length :- 
[Einstein, Whitman, Spider, Alice, Bond, Bob]

2. Using Arrays.sort() method :

  • Arrays.sort() method accepts 2 input-arguments where,
    • 1st argument is the actual String[] Arrays to be sorted
    • 2nd argument is the Comparator for sorting
  • For Sorting,
    • Override/implement compare() method of Comparator interface
    • Inside method implementation return difference of String length
  • For Ascending-order sorting,
    • subtract 2nd String length from the 1st String length
    • Syntax:- str1.length() – str2.length();
  • For Descending-order sorting,
    • subtract 1st String length from the 2nd String length
    • Syntax:- str2.length() – str1.length();
  • Print both ascending-order and descending-order sorted String[] Arrays in accordance with its String length to the console

SortingStringArraysByItsLengthUsingArraysSortMethod.java

package in.bench.resources.sorting.string.arrays;

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

public class SortingStringArraysByItsLengthUsingArraysSortMethod {

	public static void main(String[] args) {

		// 1. names with different length
		String[] names = new String[] {
				"Bond",
				"James",
				"Einstein",
				"Alice",
				"Whitman",
				"Bob",
				"Binny",
				"Spider",
				"Lee",
				"Anderson"
		};


		// 1.1 print to console
		System.out.println("Original String[] Arrays :- \n" 
				+ Arrays.toString(names) + "\n");



		// 2. sorting String[] Arrays in Ascending-order
		Arrays.sort(names, new Comparator<String>() {

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


		// 2.1 print ascending-order sorted Strings by its Length
		System.out.println("\nAscending-order Sorted String[] Arrays "
				+ "by its Length :- \n" + Arrays.toString(names) + "\n");



		// 3. sorting String[] Arrays in Descending-order
		Arrays.sort(names, new Comparator<String>() {

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


		// 3.1 print descending-order sorted Strings by its Length
		System.out.print("\nDescending-order Sorted String[] Arrays "
				+ "by its Length :- \n" + Arrays.toString(names));
	}
}

Output:

Original String[] Arrays :- 
[Bond, James, Einstein, Alice, Whitman, Bob, Binny, Spider, Lee, Anderson]


Ascending-order Sorted String[] Arrays by its Length :- 
[Bob, Lee, Bond, James, Alice, Binny, Spider, Whitman, Einstein, Anderson]


Descending-order Sorted String[] Arrays by its Length :- 
[Einstein, Anderson, Whitman, Spider, James, Alice, Binny, Bond, Bob, Lee]

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java 8 – How to Sort String[] Arrays by its length ?
Java 8 – Find all shortest Strings in List or Arrays or Stream ?