0

I have a set in apex like this

set<string> myset = new set<string>();
mySet.add('this');
mySet.add('is');
mySet.add('the');
mySet.add('example');

now i want to replace the value in the set if there is 'the'... replace it with an.

this is just an example..my set will have different data but the requirement is similar.

if there is 'the' in set ..replace it with 'an'

1 Answer 1

4

First, check if it is present, second, remove found element, third, put replacement:

Set<String> mySet = new Set<String>();
mySet.add('this');
mySet.add('is');
mySet.add('the');
mySet.add('example');

String toReplace = 'the';
String repalceWith = 'an';

if(mySet.contains(toReplace)){
    mySet.remove(toReplace);
    mySet.add(repalceWith);
}

Pay attention, Set in apex does not preserve the order in which elements have been added to a Set.

1
  • 1
    Sets are unordered, but since 2015 or so Salesforce does at least guarantee that they'll be iterated over in the same order every time you iterate over one. Doesn't really help here, but it is the closest thing sets have to an 'order'.
    – Derek F
    Nov 9, 2021 at 11:27

You must log in to answer this question.

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