2
\$\begingroup\$

I wrote the java method to answer this question : Write a Program to sort String on their length in Java? Your method should accept an array of String and return a sorted array based upon the length of String

So my questions: 1. Is my method efficient enough? 2. Can it be improved somehow?

 private static String[] sort(String [] string) {
    /*Local variables*/
    Map<String, Integer> map=new LinkedHashMap<String, Integer>();
    Map<String, Integer> mapCopy=new LinkedHashMap<String, Integer>();
    int [] lengthsArray=new int[string.length];
    String [] sortedStrings=new String[string.length];
    int counter1=0;
    int counter2=0;

    /* Store all the pairs <key,value>
     * i.e <string[i],string[i].length>
     */
    for(String s:string){
        map.put(s, s.length());
        lengthsArray[counter1]=s.length();//store all the lengths
        counter1++;

    }
    mapCopy=new LinkedHashMap<String, Integer>(map);//make a copy of map
    Arrays.sort(lengthsArray);//sort the array of lengths

    /*
     * Sort array according to the array of lengths
     * by finding the matching value from the map 
     * then add it to the final string array,and then remove it from the map 
     */
    for(int item:lengthsArray){

        for(Map.Entry<String, Integer> e:map.entrySet()){
            if(item==e.getValue()){
                sortedStrings[counter2]=e.getKey();
                counter2++;
                map.remove(e.getKey());
                break;
            }   
        }
    }

    map=mapCopy;
    System.out.println(map);//print map
    return sortedStrings;
}
\$\endgroup\$
6
\$\begingroup\$

I think you can use the Arrays.sort with Comparator to make this simple. just Override the comparator to compare the length of the array like this

public static String[] sortStrArray(String[] array){
   //sort arrays by length before returning
    Arrays.sort(array, new Comparator<String>() {
        @Override
        public int compare(String a, String b) {
            return Integer.compare(a.length(),b.length());//specifying compare type that is compare with length
        }
    });
     return array;
}

///Main Method here

String[] str = {"James","Ana","Michael","George","rose"};
    System.out.println(Arrays.toString(sortStrArray(str)));

Output:

[Ana, rose, James, George, Michael]

with Java 8

 public static String[] sortStrWithLam(String[] array){
    //sort arrays by length before returning
    Arrays.sort(array,(a,b) -> Integer.compare(a.length(),b.length()));
    return array;
}
| improve this answer | |
\$\endgroup\$
  • 1
    \$\begingroup\$ The Java 8 solution could be written using Comparator.comparingInt(). \$\endgroup\$ – 200_success Jun 18 '16 at 13:38
  • \$\begingroup\$ @200_success yea that is another way too \$\endgroup\$ – Seek Addo Jun 18 '16 at 13:56
  • 1
    \$\begingroup\$ comparingInt is a nice way to do it yes, you can do this with a one-liner: Stream.of(array).sorted(Comparator.comparingInt(String::length)).toArray(String[]::new). \$\endgroup\$ – Tunaki Jun 18 '16 at 22:13
  • \$\begingroup\$ @Tunaki yea, with just a little 'return' to it is much compact \$\endgroup\$ – Seek Addo Jun 18 '16 at 22:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy