Hi I have the String array
String version[] = {"3.1.2","2.1.7","3.1.1","3.7.3","2.6.4","1.3.4.7"};
I want to find the latest version among these. Which approach will be good? It should print 3.7.3
Hi I have the String array
String version[] = {"3.1.2","2.1.7","3.1.1","3.7.3","2.6.4","1.3.4.7"};
I want to find the latest version among these. Which approach will be good? It should print 3.7.3
Here is an example using a Comparator
public static void main(String[] args) {
String version[] = { "3.1.2", "2.1.7", "3.1222.1", "3.10.1", "3.10",
"3.7.3", "2.6.4", "1.3.4.7" };
Arrays.sort(version, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
//Split tokens into arrays
String[] tokens1 = o1.split("\\.");
String[] tokens2 = o2.split("\\.");
//Compare existing elements of each array
for (int i = 0; i < tokens1.length && i < tokens2.length; i++) {
int comparison = Integer.valueOf(tokens1[i]).compareTo(
Integer.valueOf(tokens2[i]));
if (comparison != 0) {
return comparison;
}
}
//Compare how specific each version is promote the most general
//Only considered if version lengths != in size but equal in compared tokens
return tokens1.length - tokens2.length;
}
});
for (String v : version) {
System.out.println(v);
}
}
Try this out...
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class StringSortDemo {
public static void main(String[] args) throws Exception {
String strArray[] = {"3.1.2","2.1.7","3.1.1","3.7.3","2.6.4","1.3.4.7"};
displayArray(strArray);
Arrays.sort(strArray);
displayArray(strArray);
Arrays.sort(strArray, String.CASE_INSENSITIVE_ORDER);
displayArray(strArray);
System.out.println("---------------");
List<String> strList =Arrays.asList(strArray);
displayList(strList);
Collections.sort(strList);
displayList(strList);
Collections.sort(strList, String.CASE_INSENSITIVE_ORDER);
displayList(strList);
}
public static void displayArray(String[] array) {
for (String str : array) {
System.out.print(str + " ");
}
System.out.println("The last element is "+ array[array.length-1]);
}
public static void displayList(List<String> list) {
for (String str : list) {
System.out.print(str + " ");
}
System.out.println("The last element is "+ list.get(list.size()-1));
}
}
The output is
3.1.2 2.1.7 3.1.1 3.7.3 2.6.4 1.3.4.7 The last element is 1.3.4.7
1.3.4.7 2.1.7 2.6.4 3.1.1 3.1.2 3.7.3 The last element is 3.7.3
1.3.4.7 2.1.7 2.6.4 3.1.1 3.1.2 3.7.3 The last element is 3.7.3
---------------
1.3.4.7 2.1.7 2.6.4 3.1.1 3.1.2 3.7.3 The last element is 3.7.3
1.3.4.7 2.1.7 2.6.4 3.1.1 3.1.2 3.7.3 The last element is 3.7.3
1.3.4.7 2.1.7 2.6.4 3.1.1 3.1.2 3.7.3 The last element is 3.7.3