I am trying to sort the following lines
1.0.0.0-00000000-00000 2.1.0.0 2.2.0.0 2.3.0.0-00000000-00000
These values โโare currently stored in an array of strings.
String[] arrays = {"1.0.0.0-00000000-00000", "2.1.0.0", "2.2.0.0", "2.3.0.0-00000000-00000"};
I am trying to get the output where, if there is no "-", then these values โโgo to the end of my array in sorted order. I am trying to get the output as follows:
1.0.0.0-00000000-00000 2.3.0.0-00000000-00000 2.1.0.0 2.2.0.0
I tried Arrays.sort(arrays) but I'm not sure how to do this?
import java.util.Arrays; import java.util.Comparator; import java.util.Collections; public class HelloWorld{ public static void main(String []args){ String[] arrays = {"1.0.0.0-00000000-00000", "2.1.0.0", "2.2.0.0", "2.3.0.0-00000000-00000"}; String[] newArray = new String[arrays.length]; class CustomComparator implements Comparator<String> { @Override public int compare(String a, String b) { if(a.contains("-") && !b.contains("-")) return 1; else if(!a.contains("-") && b.contains("-")) return -1; return a.compareTo(b); } } Arrays.sort(arrays, new CustomComparator()); for(String array : arrays) { System.out.println(array); } } } Error: $javac HelloWorld.java 2>&1 HelloWorld.java:25: error: no suitable method found for sort(String[],CustomComparator) Collections.sort(arrays, new CustomComparator()); ^ method Collections.<T
java sorting arrays
user3767481
source share