[英]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};
因此,我进行了一些研究,发现您可以使用数组列表和集合对年龄列表进行排序,但这没有任何用处,因为我还需要链接到其名称。
我希望你们中的任何一个可以帮助我:)
理想的解决方案是创建一个具有两个字段name
和age
的Person
类,从而使将相关数据保持在一起并进行维护变得更加轻松。
一旦使用必要的字段,构造函数和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.