简体   繁体   中英

Sort string data based on characters and its length

Can I get any easy way in java where I could arrange the alphabets in order where

a < aa < aaa < aaaa
a < b < ab < ba < aba

String.compareTo method will arrange data in the below format. Hence will not serve my purpose a < aa < aaa < b < ab < ba

Kindly help!!!

You can do it by using a Comparator

Check this:

import java.util.Comparator;
public class SComparator implements Comparator<String> {

    @Override
    public int compare(String s1, String s2) {
        if(s1.length() != s2.length()){
            return s1.length() - s2.length();
        }
        return s1.compareTo(s2);
    }

}

Then, you can use it like this:

ArrayList<String> L = new ArrayList<String>();
// ...
Collections.sort(L, new SComparator());

You could use the comparator that compares the string length and use compareTo together

        public int compare( String o1, String o2 )
        {
            if( o1.length() > o2.length() )
            {
                return 1;
            }
            else if( o1.length() < o2.length() )
            {
                return -1;
            }
            return o1.compareTo( o2 );
        }

You can solve this question through sorting as well.

String[] words = {"going", "went", "go", "how", "jam"};    
Arrays.sort(arr);

Output:

go < going < how < jam < went

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM