I have a situation where I have two separate maps. I need to use the key sets in a query. It just so happens that it's the same query for both maps. For bulkification, I want to combine the two key sets into a single set so that I can run one query instead of two.

This is easy enough:

public Set<String> combineMapKeySets(List<Map<String, String>> sourceMaps) {
    Set<String> result = new Set<String>();

    for (Map<String, String> sourceMap : sourceMaps) {
        for (String s : sourceMap.keySet()) {

    return result;

Map<String, String> map1 = new Map<String, String>();
Map<String, String> map2 = new Map<String, String>();

map1.put('Hello', 'Hello');
map2.put('World', 'World');

Set<String> strings = combineMapKeySets(new List<Map<String,String>> {
    map1, map2


This seems terribly inefficient to me however. I have tried something like the following:

Set<String> strings = map1.keySet();

However, the following error is thrown:

System.FinalException: Collection is read-only

The question is: Is there a way to combine key sets of two different maps that lays somewhere in the middle? Something that doesn't require nesting loops?

1 Answer 1


You need to instantiate one empty set into which you add the others.

Set<String> allKeys = new Set<String>();
for (Map<String, String> singleMap : allMaps)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .