Sorting an ArrayList based on the sorting of another one

前端 未结 1 402
抹茶落季
抹茶落季 2020-12-22 13:05

I have an ArrayList() in a class (GlobalDataHolder.cardNameAndDescription) and i want to sort it alphabetically but

相关标签:
1条回答
  • 2020-12-22 13:58

    It is not difficult to sort a list of indexes instead of the list itself. From that you can easily reorder the list.

    public class Test {
        List<String> testStrings = Arrays.asList(new String[]{"One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten"});
        List<Integer> testNumbers = Arrays.asList(new Integer[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10});
    
        static <T extends Comparable<T>> List<Integer> getSortOrder(List<T> list) {
            // Ints in increasing order from 0. One for each entry in the list.
            List<Integer> order = IntStream.rangeClosed(0, list.size() - 1).boxed().collect(Collectors.toList());
            Collections.sort(order, new Comparator<Integer>() {
                @Override
                public int compare(Integer o1, Integer o2) {
                    // Comparing the contents of the list at the position of the integer.
                    return list.get(o1).compareTo(list.get(o2));
                }
            });
            return order;
        }
    
        static <T> List<T> reorder(List<T> list, List<Integer> order) {
            return order.stream().map(i -> list.get(i)).collect(Collectors.toList());
        }
    
        public void test() {
            System.out.println("The strings: " + testStrings);
            List<Integer> sortOrder = getSortOrder(testStrings);
            System.out.println("The order they would be if they were sorted: " + sortOrder + " i.e. " + reorder(testStrings, sortOrder));
            List<Integer> reordered = reorder(testNumbers, sortOrder);
            System.out.println("Numbers in alphabetical order of their names: " + reordered);
        }
    
        public static void main(String[] args) {
            new Test().test();
            System.out.println("Hello");
        }
    }
    

    prints:

    The strings: [One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten]

    The order they would be if they were sorted: [7, 4, 3, 8, 0, 6, 5, 9, 2, 1] i.e. [Eight, Five, Four, Nine, One, Seven, Six, Ten, Three, Two]

    Numbers in alphabetical order of their names: [8, 5, 4, 9, 1, 7, 6, 10, 3, 2]

    I leave it up to you to add a custom comparator if you feel you need one.

    0 讨论(0)
提交回复
热议问题