Let’s check with some examples,
List<sobject> results = Database.query('Select Id From Account Limit 5'); Set<Id> accIds = (new Map<Id,Sobject>(results)).keyset();
In second line we are creating new Map<Id,Sobject> from the results of first line, and then taking the keys from this map. Once this done, heap space is released for this map, and so it is one of the efficient method.
One Liner (Without Dynamic SOQL)
Set<Id> accIds = (new Map<Id,Account>([Select Id from Account Limit 5])).keyset();
One Liner (With Dynamic SOQL)
String sQuery = 'Select Id from Account Limit 5'; Set<Id> accIds = (new Map<Id,Account>((List<Account>)Database.Query(sQuery))).keySet();