2

I'm just wondering whether it is possible to create for instance a flexible flattenSets method in Apex.

This method should take a list of sets no matter what type, and return a single set.

Example:

    public static Set<Object> flattenSets(List<Set<Object>> sets) {
        Set<Object> flattenedSet = new Set<Object>();
        for(Set<Object> singleSet: sets) {
            flattenedSet.addAll(singleSet);
        }
        return flattenedSet;
    }
3
  • Did you try it and see what happens?
    – cropredy
    Mar 21, 2022 at 8:23
  • 1
    It probably won't be possible without a lot of extra behaviour in the caller because you generally cannot cast the Set<Object> to Set<SpecificType> and vice versa. The caller would have to basically create a Set<Object> and populate it via iteration, call, then convert the returned Set in the reverse manner.
    – Phil W
    Mar 21, 2022 at 8:28
  • @PhilW One of the most maddeningly frustrating bug of Apex is definitely how it operates on class inheritance.
    – sfdcfox
    Mar 21, 2022 at 8:38

1 Answer 1

3

There is a bug in Apex that prevents Set, List, and Map objects from casting properly between various types. The type system is still at least as messed up as it was at the time of my answer (linked above).

There is a sort of solution you can use, but your milage may vary:

public Set<Object> flattenToSet(List<Object> sets) {
    Set<Object> results = new Set<Object>();
    for(Object theIterable: sets) {
        Iterator<Object> it = ((Iterable<Object>)(theIterable)).iterator();
        while(it.hasNext()) {
            results.add(it.next());
        }
    }
    return results;
}

This accepts both lists and strings of any data type. Be aware that you won't be able to cast that Set<Object> to any other type, it won't play nicely with addAll, etc. Unfortunately, until the bug is fixed, that's about the best code you can write right now, and it's still horribly inefficient compared to specialized versions.

You must log in to answer this question.

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