I have a String array where there is a white space in the middle. I want to sort the contents based on the first substring before the white space, and then the substring after the white space.
For example, if my array looks like this: {"Henry 123", "Henry 234", "David 123", "David 234"}, in the end I want {"David 123", "David 234", "Henry 123", "Henry 234"}.
I tried implement a new comparator below:
import java.util.*;
public class MyClass {
public static void main(String args[]) {
String[] str_arr = {"Henry 123", "Henry 234", "David 123", "David 234"};
Collections.sort(str_arr, new Comparator<String>(){
public int compare(String s1, String s2) {
String[] str1 = s1.split(" ");
String[] str2 = s2.split(" ");
if(str1[0].compareTo(str2[0]) != 0) {
return str1[0].compareTo(str2[0]);
}
return str1[1].compareTo(str2[1]);
}
});
for (int i = 0; i < str_arr.length; i++) {
System.out.printf("%s, ", str_arr[i]);
}
}
}
But I am getting this error:
MyClass.java:7: error: no suitable method found for sort(String[],<anonymous Comparator>) Collections.sort(str_arr, new Comparator(){ ^ method Collections.<T#1>sort(List<T#1>) is not applicable (cannot infer type-variable(s) T#1 (actual and formal argument lists differ in length)) method Collections.<T#2>sort(List<T#2>,Comparator<? super T#2>) is not applicable (cannot infer type-variable(s) T#2 (argument mismatch; String[] cannot be converted to List<T#2>)) where T#1,T#2 are type-variables: T#1 extends Comparable<? super T#1> declared in method <T#1>sort(List<T#1>) T#2 extends Object declared in method <T#2>sort(List<T#2>,Comparator<? super T#2>) 1 error
This error sounds like Collections framework does not support sorting strings, which does not make much sense.
{ "Henry 123", "Henry 23", "David 53", "David 234" }to be sorted? Please show expected result.