简体   繁体   English

首先对Array By变量进行排序,然后按降序对其进行排序

[英]Sort Array By variable in the first then sort it descending order

Hey guys here is my question. 大家好,这是我的问题。 im using JCombobox. 即时通讯使用JCombobox。 if a student have CB grade in the lesson,it should be appear in the jcombobox first , like that CB AA BA BB CC DC DD FD FF if student have DD grade it should be shown like that DD AA BA BB CB CC DC FD FF. 如果学生在本课程中获得CB成绩,则应首先出现在jcombobox中,例如该CB AA BA BB CC DC DD FD FF如果该学生具有DD成绩,则应显示为DD AA BA BB CB CC DC FD FF 。

Here all Array members 这里所有数组成员

String[] subset = new String[]{"AA", "BA", "BB", "CB", "CC", "DC", "DD", "FD", "FF"}; String []子集= new String [] {“ AA”,“ BA”,“ BB”,“ CB”,“ CC”,“ DC”,“ DD”,“ FD”,“ FF”}};

if a student have BB grade in the lesson array should be sorted like that BB AA BA BB CB CC DC DD FD FF. 如果学生在课程组中获得BB成绩,则应按照BB AA BA BB CB CC DC DD FD FF的顺序进行排序。 these mean array should be sorted by student grade in the first element of array. 这些平均数组应在数组的第一个元素中按学生成绩排序。 then it should be sorted by descending order. 然后应按降序排序。

i asked sorting arrray because jcombobox work on that. 我问排序错误,因为jcombobox可以解决这个问题。 is there a function or method which do that ? 有功能或方法吗?

thanks. 谢谢。

How about this: 这个怎么样:

public static String[] getCustomSortArray(String grade, String[] grades)
{
    int index = -1;
    for(int i = 0; i < grades.length; i++)
    {
        if(grades[i].equals(grade))
        {
            index = i;
            break;
        }
    }

    if(index == -1) return grades;

    String temp = new String[grades.length];
    temp[0] = grades[index];

    int counter = 1;
    for(int i = 0; i < grades.length; i++)
    {
        if(i != index) temp[counter++] = grades[i];
    }
    return temp;
}

I didn't test it, but I think it works. 我没有测试它,但我认为它可行。

您始终可以使用Arrays.sort()根据给定的Comparator对数组中的元素进行排序,在这种情况下,您需要根据自己的需要设计比较器。

for sorting array you can use, it uses compareTo() method of Comparable interface for sorting. 对于可以使用的数组排序,它使用Comparable接口的compareTo()方法进行排序。

Arrays.sort(array);

For descending sorting you can use Collections.reverseOrder() comparator. 对于降序排序,可以使用Collections.reverseOrder()比较器。

If I understand you right this comparator can work for you. 如果我理解您的权利,那么该比较器可以为您工作。

        Object yourComparator = new Comparator<Comparable<Object>>() {
            @Override
            public int compare(Comparable<Object> c1, Comparable<Object> c2) {
                if(c1.equals(variable)){
                    return 1;
                }
                else if(c2.equals(variable)){
                    return -1;
                }
                else {
                    return c2.compareTo(c1);
                }

            }



        };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM