The ideal solution would be to create a Person class with two fields name and age, therefore making life much easier both in keeping related data together and for maintenance.
once the class is constructed with the necessary fields, constructor(s) and getters then you can spin up however many objects required populating it with the necessary data and store this into an array or a list.
example of the class:
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;
}
}
an array of People, although you can use a list as well:
Person[] people = new Person[]{
new Person("Martin", 22),
new Person("Josef", 19),
new Person("John", 20),
new Person("Jessica", 17),
new Person("Claire", 21)
};
now you can sort by age and maintain related data like this:
// 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));
class Person { int age; String name; }and store instances of that in an array.Comparableinterface and make thecompareTomethod sort by theagefield.nameand anagefield and create a collection (or an array) for that model type. It would then be easier to sort it.