0

I have seen similar questions but still don't quite understand how to do this.

    public static Object[] dbSort(Object[] a){
       Arrays.sort(a);
        return a;
    }

when given an object array that can contain either just numbers or just strings or both how can I sort it so numbers-> smallest to biggest, strings sorted according to the alphabet, and if both then numbers sorted first and then strings.

in the code above it only works if it is a integers in the object array otherwise it gives an error since it can't sort strings as well(i think).

here are some examples to make it more clear about what I want.

given {6, 2, 3, 4, 5} should return {2, 3, 4, 5, 6}},


given {14, 32, 3, 5, 5} should return {3, 5, 5, 14, 32}},


given {1, 2, 3, 4, 5} should return {1, 2, 3, 4, 5}


given {"Banana", "Orange", "Apple", "Mango", 0, 2, 2} should return {0, 2, 2, "Apple", "Banana", "Mango", "Orange"}}


given {"C", "W", "W", "W", 1, 2, 0} should return {0,1,2,"C","W","W","W"}
Rocky cohn
  • 71
  • 1
  • 13

1 Answers1

2

You can use custom Comparator<Object> and write logic to do that like below

public static Object[] dbSort(Object[] a){
        Arrays.sort(a, new Comparator<Object>() {
            @Override
            public int compare(Object o1, Object o2) {
                if(o1 instanceof Integer && o2 instanceof Integer) {//both are integers
                    return ((int) o1) -  ((int) o2);
                }else if(o1 instanceof Integer){//second is String
                    return -1;
                }else if(o2 instanceof Integer){//first is String
                    return 1;
                }else{//both are Strings
                    return ((String) o1).compareTo((String) o2);
                }
            }
        });
        return a;
    }
}
Rajan Kali
  • 12,627
  • 3
  • 25
  • 37