Search code examples
javaarraysclassattributescompareobject

Java compare object element and if "name" attribute is same print it once


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
       
    }
}
    

Solution

  • Since you only want each name to be once, and the oldest, you can create what's called a HashMap, ( Key-> value association with unique key) in which you store only the oldest person

    Once you have this hashmap, you then can iterate through it to print exactly what you want

    Example :

    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);
    
        HashMap<String, Integer> oldest_people = new HashMap<>();
        for (Person p: persons){
            int person_age = oldest_people.getOrDefault(p.getName(), -1);
            if (person_age != -1) {
                if (p.getAge() > person_age) {
                    oldest_people.put(p.getName(), p.getAge());
                }
            }
            else {
                oldest_people.put(p.getName(), p.getAge());
            }
        }
    
    
        for (Map.Entry<String, Integer> entry : oldest_people.entrySet()) {
            System.out.println(entry.getKey() + " age : "+entry.getValue().toString());
        }
    }