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

后端 未结 10 1820
不思量自难忘°
不思量自难忘° 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-30 12:35

    In java you need to have two arrays one copy to sort off and the array you want to sort.

    with a lambda:

    String[] strings = new String[]{"string1", "string2", "string3", "string4"};
    final int[] ints = new int[]{100, 88, 92, 98};
    
    final List stringListCopy = Arrays.asList(strings);
    ArrayList sortedList = new ArrayList(stringListCopy);
    Collections.sort(sortedList, (left, right) -> ints[stringListCopy.indexOf(left)] - ints[stringListCopy.indexOf(right)]);
    

    Or with Comparator:

    String[] strings = new String[]{"string1", "string2", "string3", "string4"};
    final int[] ints = new int[]{100, 92, 88, 98};
    
    final List stringListCopy = Arrays.asList(strings);
    ArrayList sortedList = new ArrayList(stringListCopy);
    Collections.sort(sortedList, Comparator.comparing(s -> ints[stringListCopy.indexOf(s)]));
    

提交回复
热议问题