Java - Sort one array based on values of another array?

后端 未结 10 1797
不思量自难忘°
不思量自难忘° 2020-11-30 12:02

I have an array of Strings that are instances of a class from external code that I would rather not change.

I also have an array of ints that was generated by callin

10条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-30 12:19

    Maybe not exactly for that case, but for those who looking for answer how to sort one array of String based on another:

    // Array of values, in a order of sorting
    static final Map ROUNDS_SORT = new HashMap();
    static {
        ROUNDS_SORT.put("f", 0);
        ROUNDS_SORT.put("s", 1);
        ROUNDS_SORT.put("q", 2);
        ROUNDS_SORT.put("r16", 3);
        ROUNDS_SORT.put("r32", 4);
        ROUNDS_SORT.put("r64", 5);
    }
    
    // Your array to be sorted
    static ArrayList rounds = new ArrayList() {{
        add("f");
        add("q");
        add("q");
        add("r16");
        add("f");
    }};
    
    // implement
    public List getRoundsSorted() {
        Collections.sort(rounds, new Comparator() {
            @Override
            public int compare(String p1, String p2) {
                return Integer.valueOf(ROUNDS_SORT.get(p1)).compareTo(Integer.valueOf(ROUNDS_SORT.get(p2)));
            }
        });
        return rounds;
    }
    

提交回复
热议问题