Pages

Wednesday, November 10, 2021

Java 8 - Sorting An Array Of Strings By Length

1. Overview

In this tutorial, We'll learn how to sort an array of string by length in java 8.
Java 8 - Sorting An Array Of Strings By Length


2. Java 8 - Sorting An Array Of Strings By Length Using Arrays.sort()


First solution is using Arrays.sort() and Integer.compare() methods.
package com.javaprogramto.programs.strings.sort.length;

import java.util.Arrays;

public class SortStringsByLengthExample {

	public static void main(String[] args) {

		String[] words = { "hello", "how", "are", "u", "doing" };
		System.out.println("string array before sorting : "+Arrays.toString(words));
		
		
		sortArrayByLength(words, Sort.ASC);
		
		System.out.println("string array after sorting : "+Arrays.toString(words));

	}

	public static void sortArrayByLength(String[] strs, Sort direction) {
		if (direction.equals(Sort.ASC)) {
			Arrays.sort(strs, (String s1, String s2) -> Integer.compare(s1.length(), s2.length()));
		} else {
			Arrays.sort(strs, (String s1, String s2) -> (-1) * Integer.compare(s1.length(), s2.length()));
		}
	}

	public enum Sort {
		ASC, DESC
	}
}

Output:
string array before sorting : [hello, how, are, u, doing]
string array after sorting : [u, how, are, hello, doing]

3. Java 8 - Sorting An Array Of Strings By Length Using Comparator.comparingInt()


Next solution is based on the Comparator.comparingInt() method. In java 8, Comparator interface is enriched with the comparingInt() and this takes a int returned function. This int is the key for sorting.

And reversed() method also added to the Comparator interface. This function reverses the current comparator.
package com.javaprogramto.programs.strings.sort.length;

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

public class SortStringsByLengthExample2 {

	public static void main(String[] args) {

		String[] words = { "hello", "how", "are", "u", "doing" };
		System.out.println("string array before sorting : " + Arrays.toString(words));

		sortArrayByLengthUsingComparator(words, Sort.DESC);

		System.out.println("string array after sorting : " + Arrays.toString(words));

	}

	public static void sortArrayByLengthUsingComparator(String[] strs, Sort direction) {
		if (direction.equals(Sort.ASC)) {
			Arrays.sort(strs, Comparator.comparingInt(String::length));
		} else {
			Arrays.sort(strs, Comparator.comparingInt(String::length).reversed());
		}
	}

	public enum Sort {
		ASC, DESC
	}
}

Output:
string array before sorting : [hello, how, are, u, doing]
string array after sorting : [hello, doing, how, are, u]


4. Java 8 - Sorting An Array Of Strings By Length By Collecting Result using sorted() and toArray() methods


In the above solutions the result is not collected into the new array and the method type is void.
And also here the original array is sorted.

Now, in this solution the original array remain untouched with help of sorted() and toArray() methods.

Look at the below code.
package com.javaprogramto.programs.strings.sort.length;

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

public class SortStringsByLengthExample3 {

	public static void main(String[] args) {

		String[] words = { "hello", "how", "are", "u", "doing" };
		System.out.println("string array before sorting : " + Arrays.toString(words));

		String[] sortedArrayByLength = sortArrayByLengthUsingSorted(words, Sort.DESC);

		System.out.println("original array after sorting : " + Arrays.toString(words));
		System.out.println("new string array after sorting : " + Arrays.toString(sortedArrayByLength));

	}

	public static String[] sortArrayByLengthUsingSorted(String[] strs, Sort direction) {
		if (direction.equals(Sort.ASC)) {
			return Arrays.stream(strs)
					.sorted(Comparator.comparingInt(String::length))
					.toArray(String[]::new);
		} else {
			return Arrays.stream(strs)
					.sorted(Comparator.comparingInt(String::length)
					.reversed())
					.toArray(String[]::new);
		}
	}

	public enum Sort {
		ASC, DESC
	}
}

Output:
string array before sorting : [hello, how, are, u, doing]
original array after sorting : [hello, how, are, u, doing]
new string array after sorting : [hello, doing, how, are, u]


5. Conclusion


In this article, we've seen the different solutions to sort an array of string by length in java 8.



No comments:

Post a Comment

Please do not add any spam links in the comments section.