Sorting an ArrayList based on the sorting of anoth

2020-02-16 04:57发布

问题:

I have an ArrayList<String>() in a class (GlobalDataHolder.cardNameAndDescription) and i want to sort it alphabetically but i also want to sort an ArrayList<Integer>() (UserBoxGlbImageAdapter.mGLBIcons) while sorting the previously mentioned arrayList.

Sidenote: Both arrays have a size of 3(0-2).

I am writing my own custom compare() method to do this but i am not achieving what i'm looking for.When i click on the button that runs the sorting code, the correct order doesn't get achieved unless i click the button 3 times although the String ArrayList does get Alphabetically sorted. So i figured that i just need to sort the arrays as many times as the arrays's size is(so 3 times).

To sum up, the String and Integer data should be in the same order since they depend on it's other but i can't get that to work for both arrays.

None of that worked. Can someone tell me what i'm doing wrong here with the 2nd array's sorting? Here's my code:

public class SortingDialog extends DialogFragment {

@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    // Create a builder to make the dialog building process easier
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setTitle("Sorting Dialog");
    builder.setSingleChoiceItems(R.array.sorting_options, 0,
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    if (i == 1) {
                        Toast.makeText(getActivity(), "2nd option Clicked", Toast.LENGTH_SHORT).show();
                        if (getActivity().getSupportFragmentManager().findFragmentByTag("GLOBAL_FRAGMENT") != null) {
                            sortGlobalListsBasedOnNameAndDesc();
                        }
                    }
                    for (int j = 0; j < GlobalDataHolder.cardNameAndDescription.size(); j++) {
                        Log.v("card_names", GlobalDataHolder.cardNameAndDescription.get(j));
                    }
                }
            });
    builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            createToast();
            dismiss();
        }
    });
    builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            dismiss();
        }
    });
    return builder.create();
}

private void sortGlobalListsBasedOnNameAndDesc() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        GlobalDataHolder.cardNameAndDescription.sort(new Comparator<String>() {
            @Override
            public int compare(String s1, String s2) {
                int id1 = GlobalDataHolder.cardNameAndDescription.indexOf(s1);
                int id2 = GlobalDataHolder.cardNameAndDescription.indexOf(s2);

                if (s1.equals(s2)) {
                    return 0;
                } else if (s1.compareToIgnoreCase(s2) > 0) { //s1 is greater
                    //Collections.swap(UserBoxGlbImageAdapter.mGLBIcons,id2,id1);
                    swap(UserBoxGlbImageAdapter.mGLBIcons,id2,id1);
                    swap(GlobalDataHolder.cardNameAndDescription,id2,id1);
                    Log.d("case1","Called 1 time");
                    return 1;
                } else if (s1.compareToIgnoreCase(s2) < 0) { //s1 is smaller
                    //Collections.swap(UserBoxGlbImageAdapter.mGLBIcons,id1,id2);
                    swap(UserBoxGlbImageAdapter.mGLBIcons,id1,id2);
                    swap(GlobalDataHolder.cardNameAndDescription,id1,id2);
                    Log.d("case2","Called 1 time");
                    return -1;
                } else {
                    return 0;
                }
            }
        });
    }
}

private void swap(List list,int objIndex1, int objIndex2) {
    for (int i=0;i < list.size(); i++) {
        Collections.swap(list,objIndex1,objIndex2);
        UserBoxGlbImageAdapter.refreshFragmentView(UserBoxGLBFragment.getUserBoxAdapter());
    }
}

private void createToast() {
    Toast.makeText(getActivity(), "Cards sorted based on AVG Stats", Toast.LENGTH_SHORT).show();
}
}

回答1:

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.