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;
}
1 Answer 1
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;
}
-
1\$\begingroup\$ The Java 8 solution could be written using
Comparator.comparingInt()
. \$\endgroup\$200_success– 200_success2016年06月18日 13:38:43 +00:00Commented Jun 18, 2016 at 13:38 -
\$\begingroup\$ @200_success yea that is another way too \$\endgroup\$Seek Addo– Seek Addo2016年06月18日 13:56:24 +00:00Commented Jun 18, 2016 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– Tunaki2016年06月18日 22:13:50 +00:00Commented Jun 18, 2016 at 22:13 -
\$\begingroup\$ @Tunaki yea, with just a little 'return' to it is much compact \$\endgroup\$Seek Addo– Seek Addo2016年06月18日 22:25:09 +00:00Commented Jun 18, 2016 at 22:25