0

How can I combine two lists of maps so that only the unique values in the list remain? I thought about doing some nested for loops to compare the two lists, but it seems a bit messy. Is there a better way to do this.

Obviously just adding to the list doesn't give me unique values. MapList.addAll(mapList2);

3

A Set<Map<String, String>> can contain and deduplicate Map<String, String> by their contents. When working with Set, keep in mind how it determines object identity:

Uniqueness of all other non-primitive types is determined by comparing the objects’ fields.

As an illustration, you can do

Set<Map<String, String>> s = new Set<Map<String, String>>();

Map<String,String> m1 = new Map<String, String> {
    'Test' => 'Foo'
};

Map<String,String> m2 = new Map<String, String> {
    'Test' => 'Foo'
};

s.add(m1);
System.debug('s contains m2? ' + String.valueOf(s.contains(m2)));

You'll get back true; the two Map instances are considered equal because they have the same field values.

You can get a deduplicated Set<Map<String, String>> from a two List<Map<String, String>> objects by doing

Set<Map<String, String>> s = new Set<Map<String, String>>(myList);
s.addAll(myOtherList):

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.