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

后端 未结 10 1821
不思量自难忘°
不思量自难忘° 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:34

    Make a TreeMap> where the map key is the values in B, and the map values are the values in A (using a list to allow for duplicate keys). It will be sorted in the order of B by definition.

    public static void main(String[] args) {
      String[] strings = { "string1", "string2", "string3", "string4" };
      int[] ints = { 40, 32, 32, 34 };
      System.out.println(Arrays.toString(getSortedStringArray(strings, ints)));
    }
    
    public static String[] getSortedStringArray(String[] strings, int[] order) {
      Map> map = new TreeMap<>();
      for (int i = 0; i < strings.length; i++) {
        if (!map.containsKey(order[i])) {
          map.put(order[i], new LinkedList());
        }
        map.get(order[i]).add(strings[i]);
      }
      String[] ret = new String[strings.length];
      int i = 0;
      for (Map.Entry> mapEntry : map.entrySet()) {
        for (String s : mapEntry.getValue()) {
          ret[i++] = s;
        }
      }
      return ret;
    }
    

提交回复
热议问题