Java – How to Sort String List by its length ?

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

Sorting String List by its length:

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

1. Using TreeSet :

  • There is a String List 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 List elements to newly created TreeSet using addAll() method
  • Descending-order sorting :
    • Create TreeSet passing Comparator as constructor-argument with descending-order of String length logic
    • Add original String List elements to newly created TreeSet using addAll() method
  • Print TreeSet object to the console for both ascending-order and descending-order of String List in accordance with its String length
  • Note: If there are multiple Strings of same length in the String List 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

SortingStringListByItsLengthUsingTreeSet.java

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

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

public class SortingStringListByItsLengthUsingTreeSet {

	public static void main(String[] args) {

		// 1. names with different length
		List<String> names = Arrays.asList(
				"Bond",
				"Einstein",
				"Alice",
				"Whitman",
				"Lee",
				"Spider"
				);


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



		// 2. sorting String List 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 List items to TreeSet
		treeSetAsc.addAll(names);


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



		// 3. sorting String List 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 List items to TreeSet
		treeSetDesc.addAll(names);


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

Output:

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


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


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

2. Using Collections.sort() method :

  • Collections.sort() method accepts 2 input-arguments where,
    • 1st argument is the actual String List 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 List in accordance with its String length to the console

SortingStringListByItsLengthUsingCollectionsSortMethod.java

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

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

public class SortingStringListByItsLengthUsingCollectionsSortMethod {

	public static void main(String[] args) {

		// 1. names with different length
		List<String> names = Arrays.asList(
				"Bond",
				"James",
				"Einstein",
				"Alice",
				"Whitman",
				"Bob",
				"Binny",
				"Spider",
				"Lee",
				"Anderson"
				);


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



		// 2. sorting String List in Ascending-order
		Collections.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 List "
				+ "by its Length :- \n" + names + "\n");



		// 3. sorting String List in Descending-order
		Collections.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 List "
				+ "by its Length :- \n" + names);
	}
}

Output:

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


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


Descending-order Sorted String List 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 List by its length ?
Java 8 – How to Sort String[] Arrays by its length ?