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

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

    In java 8, you can do this

    with a lambda:

        String[] strings = new String[]{"string1", "string2", "string3"};
        final int[] ints = new int[]{40, 32, 34};
    
        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 better, with Comparator:

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

提交回复
热议问题