Is it possible to compare attributes of objects in a list & if the attribute "name" happens to be the same then print out the one that is older (with the rest that does not have same name) and if their name & age happens to be the same then print out one of them (with the rest that does not have same name)? I need to compare a list with objects. I sorted the list and started with nestled for-loops but then got stuck. Are there better ways of doing this? Maybe placing some method in the Person class or another way?
enter code here
public 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;
}
}
public class Main {
public static void main(String[] args){
Person[] persons = new Student[4];
persons[0] = new Person("Erik",20);
persons[1] = new Person("Bob",21);
persons[2] = new Person("Erik",25);
persons[3] = new Person("Fredrik",20);
Arrays.sort(persons, Comparator.comparing(Person::getName));
for (int i = 0; i<persons.length; i++)
for(int j = 0; j<i; j++){
if (persons[i].getAge() == persons[j].getAge())
}
//output: Bob, Erik, Fredrik
}
}