sort an array with float and string

I have a array: 0, a, b, 1.2, 0.2, c
I'd like to sort them by number first, then by alphabetic
result should be:
0, 0.2, 1.2, a, b, c

How can I do this?
xiaoyunwuAsked:
Who is Participating?
 
for_yanCommented:
You define Comparator which aligns the strings this way and then
use method Arrays.sort(array, Comparator)

0
 
xiaoyunwuAuthor Commented:
Thanks!
0
Cloud Class® Course: Amazon Web Services - Basic

Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface.

 
CEHJCommented:
Neither of those answers will help you unfortunately
0
 
xiaoyunwuAuthor Commented:
I've tried out, and it worked. Thanks.
0
 
for_yanCommented:
This is the class with static method sortArray, which would sort
your array in the sense you want it (see output):

import java.util.Arrays;

public class MyString implements Comparable<MyString>  {
    String s;
    public MyString(String s){
        this.s = s;
    }

    public String getString(){ return s;}

    public int compareTo(MyString ms1){
     float f = -1.0f;
     float f1 = -1.0f;
      String s1 = ms1.getString();
        boolean first = true;
        boolean second = true;

        try{
            f = Float.parseFloat(s);
        } catch(Exception ex){
            first = false;
        }

        try{
             f1 = Float.parseFloat(s1);
         } catch(Exception ex){
             second = false;
         }

        if(first && !second)return -1;
        if(!first && second)return 1;
        if(first && second){
            if(f<f1)return -1;
            else return 1;
        }
        if((!first) && (!second)){
            return s.compareTo(s1);
        }

      return 1;
    }

    public static String [] sortArray(String [] arr){
        MyString[] myss = new MyString[arr.length];
       for(int j=0; j<arr.length; j++){
           myss[j]= new MyString(arr[j]);
       }

        Arrays.sort(myss);
        String [] ss = new String[myss.length];

          for(int j=0; j<arr.length; j++){
           ss[j]= myss[j].getString();
       }

        return ss;

    }

    public static void main(String[] args) {
        String [] ss = { "0", "c", "b", "1.2", "0.2", "a"};
        ss = MyString.sortArray(ss);
        for(String s: ss){
            System.out.println(s);
        }

    }

}

Open in new window


Output:
0
0.2
1.2
a
b
c

Open in new window

0
 
xiaoyunwuAuthor Commented:
Thank you very much, for_yan.
0
 
for_yanCommented:
You are always welcome.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.