簡體   English   中英

以相同方式對兩個列表進行排序

[英]Sorting two lists in the same way

好的,所以我有2個輸入參數:

String[] Names = {"Martin", "Josef", "John", "Jessica", "Claire"};
int[] Age = {22, 19, 20, 17, 21};

我想要的輸出是一個看起來像這樣的列表:

String[] Names = {"Jessica", "Josef", "John", "Claire", "Martin"};
int[] Age = {17, 19, 20, 21, 22};

因此,我進行了一些研究,發現您可以使用數組列表和集合對年齡列表進行排序,但這沒有任何用處,因為我還需要鏈接到其名稱。

我希望你們中的任何一個可以幫助我:)

理想的解決方案是創建一個具有兩個字段nameagePerson類,從而使將相關數據保持在一起並進行維護變得更加輕松。

一旦使用必要的字段,構造函數和getter構造了類,您就可以旋轉許多所需的對象,並在其中填充必要的數據並將其存儲到數組或列表中。

類的例子:

public class Person {
     private String name;
     private int age;

     @Override
     public String toString() {
         return "Person{" +
                 "name='" + name + '\'' +
                 ", age=" + age +
                 '}';
     }

     public Person(String name, int age) {
        this.name = name;
        this.age = age;
     }

     public String getName() {
        return name;
     }

     public int getAge() {
        return age;
     }
}

一組人,盡管您也可以使用列表:

Person[] people = new Person[]{
        new Person("Martin", 22),
        new Person("Josef", 19),
        new Person("John", 20),
        new Person("Jessica", 17),
        new Person("Claire", 21)
};

現在您可以按年齡排序並維護相關數據,如下所示:

// if you're using an array
Arrays.sort(people, Comparator.comparingInt(Person::getAge));

// if you're using a list
people.sort(Comparator.comparingInt(Person::getAge));

為持有年齡和姓名的Person創建一個類,將其放入一個排序集中,並創建一個自定義編譯器

public class F {
    public static void main(String[] args) {
        SortedSet<Person> people = new TreeSet<Person>((o1, o2) -> o1.getAge() - o2.getAge());
        people.add(new Person("foo", 3));
        people.add(new Person("bar", 2));

        System.out.println(people);
    }

    private static class Person {
        private String name;
        private int age;

        public Person(String name, int age) {
            this.name = name;
            this.age = age;
        }

        public String getName() {
            return name;
        }

        public int getAge() {
            return age;
        }

        @Override
        public String toString() {
            return MoreObjects.toStringHelper(this)
                    .add("name", name)
                    .add("age", age)
                    .toString();
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM