【问题标题】:Sorting an ArrayList based on the sorting of another one根据另一个数组的排序对 ArrayList 进行排序
【发布时间】:2018-07-13 03:14:21
【问题描述】:

我在一个班级 (GlobalDataHolder.cardNameAndDescription) 中有一个ArrayList<String>(),我想按字母顺序对其进行排序,但我也想排序一个ArrayList<Integer>() (@ 987654324@) 同时对前面提到的arrayList 进行排序。

旁注:两个数组的大小都是 3(0-2)。

我正在编写自己的自定义 compare() 方法来执行此操作,但我没有实现我想要的。当我单击运行排序代码的按钮时,正确的顺序没有实现除非我点击按钮 3 次,尽管 String ArrayList 确实得到按字母顺序排序。所以我想我只需要将数组排序与数组大小一样多(所以 3 次)。

总而言之,字符串和整数数据的顺序应该相同,因为它们依赖于其他数据,但我无法让它对两个数组都起作用。

这些都不起作用。有人可以告诉我第二个数组的排序我在做什么错吗?这是我的代码:

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();
}
}

【问题讨论】:

  • 看起来你的字符串和你的整数以某种方式连接起来。所以你可能想用一个字符串和一个整数变量创建一个自定义类,把那个对象放入一个丢失的对象中,然后按字符串值对其进行排序。 Java 是一种面向对象 编程语言,所以要使用对象!
  • @TimothyTruckle 那些数组列表在我的数据库中,重要的是不要把它们混为一个对象。
  • 您需要在数组中的字符串和整数之间建立某种联系之王吗?您可以分两步完成,首先对字符串数组进行排序,然后根据该顺序对整数进行排序。
  • @Dimitri 基本上我已经对字符串列表进行了排序,但是我无法正确排序第二个列表。我想我对索引部分感到困惑,如何正确获取它们并使用它们以正确的顺序交换第二个列表的元素。

标签: java android arrays sorting arraylist


【解决方案1】:

排序索引列表而不是列表本身并不难。从中您可以轻松地重新排序列表。

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");
    }
}

打印:

弦乐:[一、二、三、四、五、六、七、八、九、十]

如果它们被排序,它们的顺序是:[7, 4, 3, 8, 0, 6, 5, 9, 2, 1] 即 [八, 五, 四, 九, 一, 七, 六,十、三、二]

按名称字母顺序排列的数字:[8, 5, 4, 9, 1, 7, 6, 10, 3, 2]

如果您觉得需要,我让您自行添加自定义比较器。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-10
    • 1970-01-01
    • 1970-01-01
    • 2015-08-05
    • 1970-01-01
    • 1970-01-01
    • 2013-12-24
    • 2015-06-08
    相关资源
    最近更新 更多