Sort array strings by length each string shortest strings first

Most languages have a built in sort method that will sort an array of strings alphabetically. Demonstrate how to sort an array of strings by the length of each string, shortest strings first.

Solution: Please have java program below:

package com.javahonk;

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

public class SortStringByLength implements Comparator<String> {

    public static void main(String[] args) {

        List<String> list = new ArrayList<String>();
        list.add("aghkafgklt2");
        list.add("dfghako");
        list.add("qwemnaarkf");

        Collections.sort(list, new SortStringByLength());
        for (String string : list) {
            System.out.println(string);
        }

    }

    @Override
    public int compare(String o1, String o2) {

        return o1.length() - o2.length();
    }

}

Output:

Sort array strings by length each string shortest strings first

Leave a Reply

Your email address will not be published. Required fields are marked *