[SalesForce] List of IDs from List

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.

Best Answer

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.

Related Topic