Search code examples
javakotlinassertj

Check lists of objects for equality without order check in their List property


Preconditions: I am deserializing a complex JSON into data class. The destination class has a bit of a complex hierarchy.

I have a list of objects List. Where ServiceFeature is the following (it's in kotlin, but does not matter):

data class ServiceFeature(
    val flagValue: String?,
    val effectiveFlagValue: String?,
    val name: String?,
    val attributes: List<Attribute?>?
)

As you can see ServiceFeature has an "attributes" property which includes another List of "Attribute". The main point is that Attributes in list might be in any order. Is there a reliable way to compare two lists of ServiceFeatures without order check from List<Attribute?>

I am trying to find a solution with assertJ.


Solution

  • If order does not matter for your attributes and they are unique (i.e. may not have multiple attributes of the same type) you might change the structure into a Set<Attribute?> instead and just use the regular compare.

    If you want to preserve order but compare (unique) attributes you may convert them to set when comparing, see Easiest way to convert a List to a Set in Java.