There are a few different ways to do this but recently I came across a really easy way that I thought I should share with everyone!
In this example I have an Account and I have another object called AccountChild__c. The Account object has a field called ExternalID__c (which is an External Id field) and the AccountChild object has a field called Account__c which is the lookup to the Account.
When I create the AccountChild record in apex, I want to populate the Account lookup using the external id as I know the external id but not the actual Account Id. Doing this saves me a query and a loop to find and populate this information.
AccountChild__c childRecord = new AccountChild__c();
childRecord.putSObject(‘Account__r’, new Account(ExternalID__c = extID));
childRecord.Name = ‘Name’;
In the example above, I was able to insert a child record and populate the account lookup using the external id on the account instead of the account id. If I know the external id already, this saves me doing a query to find the account ids and reduces the complexity of the code.