Code Review Stack Exchange is a question and answer site for peer programmer code reviews. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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;
}
share|improve this question

migrated from stackoverflow.com Jun 18 at 13:25

This question came from our site for professional and enthusiast programmers.

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;
}
share|improve this answer
    
+1 for multiple answers that utilize the language's functionality well. However, you should point out that this method (both of them) will mutate the input array via Arrays.sort(). – nasukkin Jun 17 at 23:36
    
@nasukkin thanks, i will add that – Seek Addo Jun 17 at 23:38
    
@siyabongamdletshe you welcome, can you accept the answer if is ok for you – Seek Addo Jun 17 at 23:48
1  
The Java 8 solution could be written using Comparator.comparingInt(). – 200_success Jun 18 at 13:38
1  
comparingInt is a nice way to do it yes, you can do this with a one-liner: Stream.of(array).sorted(Comparator.comparingInt(String::leng‌​th)).toArray(String[‌​]::new). – Tunaki Jun 18 at 22:13

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.