Home > Enterprise >  How can I check if a specific fields of objects within an array or list are unique?
How can I check if a specific fields of objects within an array or list are unique?

Time:11-25

If I have a list of objects like this,

person = [
    a = {
        name = john
        address = bakerfield
        phone = 1234
    },
    b = {
        name = stacy
        address = cloverfield
        phone = 4567
    },
    .
    .
    .
    .
]

I want to return true if all object's name and address fields are unique. It should return true if an object has same name but different address or vice versa.

I am fairly new to Java so having hard time figuring this one out. I tried implementing this with contains method but that didn't work.

Edit: fixed json formatting to object

Edit 2: I was able to solve this problem using Comparator.comparing along with TreeSet<>.

CodePudding user response:

Firstly you need to write a proper equals (and hashCode also! Read the first link below) method in your Person class that will compare all fields to understand whether the instance is duplicate or not.

When you will do this you can use a feature of java Set collection that guarantees that you will have only one instance of the object inside (the duplicate will be "ignored" when added) and compare the size of your initial array/list and the set created on this array/list

List<Person> people = someDeserializeJsonMethod();
return people.size() == new HashSet<>(people).size();

Read more:

CodePudding user response:

When you say you have a list. Do you mean you have: List<Person> person;?

Because you say you are trying to use contains. Contains compares objects, not values in objects. For example if I had an ArrayList of strings.

ArrayList<String> colors = new ArrayList<>;

And I had some strings like:

String a = "red";
String b = "blue";
String c = "green";
String d = "green";

Then added a,b,c to the ArrayList, but left out d.

colors.add(a);
colors.add(b);
colors.add(c);

With the objects now in the arraylist. I can use compare like this:

colors.contains(a)

This will return true because the object 'a' is in the ArrayList. But if you try colors.contains(d) it'll return false. Even though the value of 'c' is 'green' which is the same value as 'd'. It isn't the same object. Because '.contains()' is just comparing objects and not the value of the object.

If you want to compare the values of a list/arrayList than you will have to a For loop.

public boolean comparePerson(ArrayList<Person> persons, Person person) {
//persons is your main list. And person is a single person that you want to see if they are in the ArrayList.

for (Person p: persons) {
    if (person.name == p.name) {
        if (person.address == p.address) {
        return true;
        }
    }
}
return false;
}

Optionally this is why having an Id field is useful. You'll only need to compare Ids and not multiple fields for a confident match.

  • Related