如何将一个int数组和一个字符串数组排序为一个排序的字符串数组

时间:2018-11-16 19:12:11

标签: java arrays

0

输出:

class Main {

    public static void main(String[] args) {
        String firstName[] = { "Adaline", "Almeda", "Alyce", "Amos", "Anneliese", "Antoinette" };
        String lastName[] = { "Aker", "Austria", "Arvin", "Amerine", "Atnip", "Abbate" };
        int englishGrade[] = { 99, 86, 72, 90, 73, 84 };

        for (int i = 0; i < lastName.length; i++) {
            Arrays.sort(lastName);
            System.out.println(lastName[i]);
        }
    }
}

想按姓氏排序,使其输出在ex之上。告诉我寻找答案的步骤。

1 个答案:

答案 0 :(得分:2)

首先,您应该避免使用这样的数组。最好创建对象,例如PersonGrade并为每个人创建一个实例。

public static final class PersonGrade {

    private final String firstName;
    private final String lastName;
    private final int englishGrade;

    public PersonGrade(String firstName, String lastName, int englishGrade) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.englishGrade = englishGrade;
    }
}

然后定义所需的比较器,例如按姓氏asc比较:

private static final Comparator<PersonGrade> COMPARE_BY_LAST_NAME = (p1, p2) -> p1.lastName.compareToIgnoreCase(p2.lastName);

最后,您可以将所有牧师添加到列表中,然后使用给定的比较器对其进行排序,或使用给定的比较器创建TreeSet并向其中添加所有人员(这是二进制尝试,所有人员将自动排序):

Set<PersonGrade> persons = new TreeSet<>(COMPARE_BY_LAST_NAME);
persons.add(new PersonGrade("Adaline", "Aker", 99));
persons.add(new PersonGrade("Almeda", "Austria", 86));
persons.add(new PersonGrade("Alyce", "Arvin", 72));
persons.add(new PersonGrade("Amos", "Amerine", 90));
persons.add(new PersonGrade("Anneliese", "Atnip", 73));
persons.add(new PersonGrade("Antoinette", "Abbate", 84));

persons.forEach(person -> System.out.println(person.firstName + ' ' + person.lastName + ' ' + person.englishGrade));

PS

这是使用数组解决问题的方法。

public static void sortByLastName(String[] firstNames, String[] lastNames, int[] englishGrades) {
    class PersonGrade implements Comparable<PersonGrade> {

        final String firstName;
        final String lastName;
        final int englishGrade;

        public PersonGrade(String firstName, String lastName, int englishGrade) {
            this.firstName = firstName;
            this.lastName = lastName;
            this.englishGrade = englishGrade;
        }

        @Override
        public int compareTo(PersonGrade p) {
            return lastName.compareToIgnoreCase(p.lastName);
        }

        @Override
        public String toString() {
            return firstName + ' ' + lastName + ' ' + englishGrade;
        }
    }

    Set<PersonGrade> persons = new TreeSet<>();

    for (int i = 0; i < firstNames.length; i++)
        persons.add(new PersonGrade(firstNames[i], lastNames[i], englishGrades[i]));

    int i = 0;

    for (PersonGrade person : persons) {
        firstNames[i] = person.firstName;
        lastNames[i] = person.lastName;
        englishGrades[i] = person.englishGrade;
        i++;
    }
}