2

I have a List of sObjects (User) and need to put the ID of each record in this List into a separate List of type String.

I found this related question and answer, but this puts the ID into a Set (I need it into a List) - the code from this that's not working is below.

List<User> users = [SELECT Id, Name, ContactId FROM User];
List<String> userIds = (new Map<Id,User>(users)).keySet();

Thanks in advance for your assistance.

7

Apex lists have a constructor that takes a set as an argument to you can do this to end up with a list rather than a set:

List<Id> userIds = new List<Id>(new Map<Id, User>(users).keySet());

(This also relies on this convenience map constructor.)

Note that although you can use the string type for ID values, it is clearer to use the ID class and that also allows ID-specific methods to be invoked.

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.