Close

Java Collections - How to Sort List/Array of Strings by length?

[Last Updated: Nov 8, 2025]

Java Collections Java 

This example shows how to sort strings of list or array by length. It's based on Java 1.8 functions and new Comparator API.

package com.logicbig.example;

import java.util.*;

public class SortByStringLength {

public static void main(String[] args) {
sortStringArrayByLength(new String[]{"0ab", "cdef", "ab", "abcdefg"});
sortStringListByLength(new ArrayList<>(
Arrays.asList("0ab", "cdef", "ab", "abcdefg")));
}

private static void sortStringListByLength(List<String> list) {
System.out.println("-- sorting list of string --");
Collections.sort(list, Comparator.comparing(String::length));
list.forEach(System.out::println);
}

private static void sortStringArrayByLength(String[] stringArray) {
System.out.println("-- sorting array of string --");
Arrays.sort(stringArray, Comparator.comparing(String::length));
Arrays.stream(stringArray).forEach(System.out::println);
}
}

Output

-- sorting array of string --
ab
0ab
cdef
abcdefg
-- sorting list of string --
ab
0ab
cdef
abcdefg




See Also