简体   繁体   中英

Sorting 'Index' array

Can anybody tell what is the best(easy) way to sort the following string 'index' array in java

String [] menuIndex= { "0",
                       "1",
                       "2",
                       "3",
                       "0.0",
                       "0.0.1",
                       "0.0.0",
                       "0.0.4",
                       "14" ,
                       "14.0",
                       "0.1"  };
I need the sorted array in the following format
0, 
0.0, 
0.0.0,
0.0.1,
0.0.4,
0.1,
1,
2,
3,
14,
14.0

Plz help....

Since you have changed requirements, your own comparator is the right solution.

import java.util.Arrays;
import java.util.Comparator;

public class MyCmp implements Comparator<String> {

    @Override
    public int compare(String o1, String o2) {
        String[] parts1 = o1.split("\\.");
        String[] parts2 = o2.split("\\.");
        int max = Math.max(parts1.length, parts2.length);
        for (int i = 0; i < max; i++) {
            if (i < parts1.length && i < parts2.length) {
                Integer i1 = Integer.parseInt(parts1[i]);
                Integer i2 = Integer.parseInt(parts2[i]);
                if (i1 == i2)
                    continue;
                return i1.compareTo(i2);
            }
            if (i < parts1.length) {
                return 1;
            }
            if (i < parts2.length) {
                return -1;
            }
        }
        return 0;
    }

    public static void main(String[] args) {
        String[] menuIndex = { "0",
                "1",
                "2",
                "3",
                "0.0",
                "0.0.1",
                "0.0.0",
                "0.0.4",
                "14",
                "14.0",
                "0.1" };
        Arrays.sort(menuIndex, new MyCmp());
        System.out.println(Arrays.toString(menuIndex));
    }

}

创建自己的比较器并使用它对数组进行排序。

Use Arrays.sort method for sorting..below is the code.

  String [] menuIndex= { "0","1","2","3","0.0","0.0.1","0.0.0","0.0.4","4","4.0","0.1"};
            Arrays.sort(menuIndex);
            for(String str:menuIndex){
                System.out.println(str);
            }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM