Hot answers tagged

75

Generally, your lists should always be initialized. One common misconception is that queries can produce a null list, which is never true. For example, consider the following code: Account[] records = [SELECT Id, Name, AccountNumber FROM Account]; if(records!=null && !records.isEmpty()) { for(Account record: records) { // Do Something ...


29

(tl;dr at bottom) Filter Speed If you can use Map.keySet(), you'll get a Set back in about 1/10th of the time versus a loop over those same records and adding all the values. Of course, the Map<Id, SObject>(List<SObject>) constructor only works on Id, not on related ID values, which means you'd have to fall back to a loop. However, in cases ...


25

No such method currently exists on the List class as of Winter '17 (API v38). The only way to do this in Apex that I'm aware of is to loop over the list starting from the end. List<Object> someList = new List<Object>{1,2,3,4,5}; List<Object> reversed = new List<Object>(); for(Integer i = someList.size() - 1; i >= 0; i--){ ...


24

As long as you don't use the shorthand iteration technique for(Object a : Objects) and use a traditional for loop, it works fine (you must traverse the list in reverse order - thanks Willem) Try this: for (Integer i = (companyinfos.size()-1) ; i>= 0 ; i--){ String s = companyInfos[i]; if(s.contains('a')){ companyinfos.remove(i); } }


24

Since so many people have viewed this question, I wanted to provide an updated answer to this for anybody who visits this question in 2018 & beyond: The upcoming version of Salesforce (Spring '18) does add the contains() method to List: Spring '18 Release Notes: New and Changed Classes contains(listElement) Returns true if the list contains the ...


24

The following methodology may be somewhat faulty but demonstrates a large difference. The get approach is more than 4 times slower. Square Brackets List<Integer> numbers = new List<Integer>(); for (Integer i = 0; i < 1000000; i++) numbers.add(i); Integer x; Long start = Datetime.now().getTime(); for (Integer i = 0; i < 1000000; i++) x = ...


21

The idiomatic way to do this in other languages without iterator semantics is to iterate through the list backwards. For example: public static List<Object> removeAll(List<Object> target, Object toRemove) { for(Integer i = target.size() - 1; i >= 0; i--) { if(target[i].equals(toRemove)) { target.remove(i); } ...


18

I agree with Rahul's comment that the following is probably the best you can do: String payload = '{"data": [{"s": "a", "i": 1}]}'; Map<String, Object> deserialized = (Map<String, Object>)JSON.deserializeUntyped(payload); List<Map<String, Object>> data = new List<Map<String, Object>>(); for (Object instance : (List<...


16

The List class does not have a contains method. Use the Set class instead: Set<Id> userIdsToRemove = new Set<Id>(); if (!userIdsToRemove.contains(u.Id)) { /* do stuff */ }


14

Update: I missed what is probably the single most important part of the question in answering this - the "In SOQL" part. Perhaps consider this answer in terms of the other processing you are going to do with the collection before or after you pass it off to a SOQL query. Summary: Use a List when: Ordering is important You want to access elements by index ...


13

You begin your question with: I have a List<custom_object__c>. I want to convert to a Map, where the ID is the String and the value to be an custom_object__c object. Then you show us code that doesn't at all reference List<custom_object__c>. So, like others, I'm a bit confused. To help point you in the right direction, I'm going to give you an ...


12

It is generally best to avoid null values in code so using null list references to indicate empty lists isn't usually good approach. That is this code: List<String> strings = new List<String>(); ... for (String item : strings) { ... } is clearer and safer than this code: List<String> strings = null; ... if (strings != null) { for ...


12

You can't cast ANY to a more specific type, so you have to actually obtain the type that you want to return. Without proper reflection, you have to tell the function what type you'd like to return. There's several ways you can do that, but here's one way: public class Parser { public static List<List<Object>> splitList(List<Object> ...


12

The straight SOQL accounts = [select id, .. from Account ...] always returns a list You can usually avoid even having to test for list empty by coding your methods to accept lists as arguments and otherwise use for loop processing as in for (Account a: accounts) { // if accounts is empty, loop does nothing // do work } someReturnType myMethod(Account[...


12

Here's how'd I do it: public static SObject[] mergeData(SObject[] list1, SObject[] list2) { Map<Id, SObject> results = new Map<Id, SObject>(); for(SObject[] recordList: new List<SObject[]> { list2, list1 }) { for(SObject record: recordList) { results.put(record.Id, record.getSObjectType().newSobject(record.Id)); ...


11

Instantiate a new generic list and it won't carry over any type information. Simply casting to List<SObject> doesn't remove the fact it was originally a List<Account>. List<SObject> records = new List<SObject>(); records.addAll(accounts); records.addAll(opportunities);


11

Your assumption is incorrect and leadList1 will actually be an empty list. You would get an error if you tried: Lead singleLead = [SELECT Id FROM Lead LIMIT 1]; The reason such an assignment would throw an error is the query has to return exactly one row for it to work. Having zero records or 2+ leads to an error state. However, if a query assigned to a ...


11

actually, there is a difference, in current example it impacts on total number of records retrieved by SOQL queries limits. Limits is one of the most important challenge working with salesforce platform. try to use them so less, as possible. E.g. you have 50000 Accounts and you need to query only one, so that query [SELECT Id, Name, Type, ParentId, Fax, ...


11

You have to implement a Wrapper class with comparable interface for this to happen. To implement a custom sort order for sObjects in lists, create a wrapper class for the sObject and implement the Comparable interface. The wrapper class contains the sObject in question and implements the compareTo method, in which you specify the sort logic. Eg: ...


10

Instead of this code: List<Object> reqs = (List<Object>) responseObjinside3 .get('map'); List<string> lsstr= new List<string> (); for(Object a:reqs){ lsstr=(List<string>)a; } Use this code: List<Object> reqs = (List<Object>) responseObjinside3.values(); List<string> lsstr= new List<string> (); ...


10

Here are the components of that method declaration: Access Modifier - public Static vs. Instance - static Return Type - List<List<SObject>> Method Name - searchContactsAndLeads Parameters - String a You would mark this method public if you intend for it to be accessible from another Apex Class or Apex Trigger. See Access Modifiers. You would ...


10

The map's value (ProductWrapper) is incompatible with the list's value (Product2). You'd have to extract the values manually: for(ProductWrapper wrapper: mapProducts.values()) { productList.add(wrapper.product); }


10

Just for completeness, you could also implement a custom reverse iterator : public class ReverseIterator implements Iterator<Object> { public List<Object> internalRef; integer position; public ReverseIterator(List<Object> source) { internalRef = source; position = internalRef.size(); } public ...


10

You're close to the solution. The thing that you're getting caught on is that the outer loop isn't iterating over a single Opportunity, but rather a List<Opportunity> // Outer loop on a List<List<Opportunity>> gets you one level in, resulting in // a List<Opportunity> for(List<Opportunity> oppList : totalMpRecords){ // ...


10

You can supply string variable values using Apex binding. When you're not using Dynamic SOQL, as you're not here, you can even use complex Apex expressions in the bind. The following options are all legit. ... WHERE Name IN (:STRING_ONE, :stringTwo) ... WHERE Name IN :new List<String>{STRING_ONE, stringTwo} ... WHERE Name = :STRING_ONE OR Name = :...


9

Hopefully these names help explain what is going on: List<List<String>> listOfListOfString = Utility.ParseMultipleResponse(ret); for (List<String> listOfString : listOfListOfString) { for (String str : listOfString) { // Code } } Each for loop iterates over a list, so the type of the for loop variable is "one list less" in ...


9

Approach 2 would be preferred, indeed. The only scenario in which approach 1 could be considered is when it is absolutely necessary for the system to run that the record exists. E.g. in case of a configuration table. In that case you might always want an exception to happen. You could also use approach 2 for that, but approach 1 is less code for that ...


9

In your javascript controller, you can get the component using the find method and then get the attribute value of the comonent using the get method.. component.find("categoryPicklist").get("v.value"); Refer this Trailhead module for more details


9

Right now, your loop is modifying the same instance of HCPFacility in each iteration of the loop (and then storing that in the list). Lists store references of the objects you place into them (rather that independent instances), so when you change a field of the object outside of the list (HCPfac in your case), you also end up changing the field inside the ...


9

This method was introduced in the Spring '18 Release, which likely hasn't been rolled out to your org yet. You can see the calendar for major releases at https://status.salesforce.com/status. For instance, if you were on na31, this release would be rolled out Friday night (Eastern Standard Time). PS - Make sure you use API Version 42.0 or greater if you ...


Only top voted, non community-wiki answers of a minimum length are eligible