Reputation: 23
okay so I have 2 input parameters:
String[] Names = {"Martin", "Josef", "John", "Jessica", "Claire"};
int[] Age = {22, 19, 20, 17, 21};
The output I desire is a list that looks like this:
String[] Names = {"Jessica", "Josef", "John", "Claire", "Martin"};
int[] Age = {17, 19, 20, 21, 22};
So I did some research and found that you can sort the age list with array list and collections, however that won't be of any use since I also need the names linked to it.
I was hoping any of you could help me with this :)
Upvotes: 1
Views: 186
Reputation: 56489
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));
Upvotes: 2
Reputation: 73301
Create a class for Person holding age and name, put all in a sorted set and create a custom comperator
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();
}
}
}
Upvotes: 0