Hot answers tagged

152

I know only one: Map<ID, Contact> m = new Map<ID, Contact>([SELECT Id, LastName FROM Contact]); Here is the doc: Maps of sObjects


57

Simply change the round brackets: private Map<String, String> myMap = new Map<String, String>('a' => 'John', 'b' => 'Mike', 'c' => 'Eddy'); To curly brackets (and change the values to integers): private Map<String, Integer> myMap = new Map<String, Integer>{'a' => 1, 'b' => 2, 'c' => 3};


54

Alternatively, if you have a list already -- say you're in a situation where you need a map, but aren't in a mood to refactor your entire class to handle a map, you can convert your list of results to a map thusly: Map<Id,OBJ_TYPE> mapFromList = new Map<Id,OBJ_TYPE>(List_object_variable); This will generate a map from the list as if you'd ...


45

These methods are available for all maps. So one way to code it is to use a keySet() method of the Map. Firstly you will get all Id's (keys) from the map and then will iterate over that set of keys. Based on the key you can then get a corresponding set of emails: for (Id key : emailDiseaseMap.keySet()) { // The "key" variable is also available inside ...


33

As far as I'm aware the map constructor only supports ID-->Sobject. If you want a different key, then you have to build the map yourself. Map<String, PriceBook2> priceBooks = new Map<String, PriceBook2>(); for (Pricebook2 p : [SELECT name,id FROM PriceBook2 WHERE name=:priceBooksNames ]) { priceBooks.put(p.name, p); }


25

I suggest you paste your JSON into http://json2apex.herokuapp.com/ and try the generated code. This tool generates simple Apex classes with a field per JSON field and then you can parse with a single JSON.deserialize call. Here is the code produced from your JSON. (You can rename the classes as you see fit and also change data types if you know better e.g. ...


25

I use SObject as a key when I want to use a composite key. For example, say I want to find duplicates based on first name, last name, and email. I might loop through a list of contacts, and create a contact that matches the keys I'm using: Incoming.put(new Contact(FirstName= record.FirstName, LastName= record.LastName, Email= record.Email), record); Then, ...


23

If you know the structure of the JSON before you get it then the easiest way is to create a class to define the Object. For Example, given the following JSON String { "id" : "someID", "street" : "someStreet", "listOfClass" : [ { "myVar" : "test" } ] "myArray" : ["1","2","3"] } Define ...


21

Yes, that is the expected behavior. Behind the scenes, Salesforce is hashing the sObject. By changing field values, you change the hash. A better practice is to use the sObject ID as the key. This blog post explains some more: https://appirio.com/tech-blog/considerations-using-sobjects-in-sets-and-map-keys-in-apex When planning to use an SObject as the ...


21

Apex does not allow multiple return types. However, you can create a custom type to be returned from your method. It would have a Lead and a Set<Date> and a Set<String> in it - allowing you to have strings and dates per Lead. Similar to this: public class LeadWrapperThing { public Lead theLead { get; set; } public Set<...


18

I tried to replicate your problem, and ended up trying different things, no luck doing it your way (confirmed that, got a visualforce error), no luck with <apex:param> but what I ended up doing was I created a second map, with the same keys, which basically just holds the size of the list in an Integer, and get those values. Here is my code: ...


18

The pattern used depends on if you expect the map to be used or not. You have a misconception here, about "compile time vs execution time." Unlike Java, there is no optimization in Apex Code that serializes statically initialized maps. In other words, it always executes every time, and costs CPU time accordingly. The difference between the first and second ...


17

You can't directly iterate over map. You need to do something like Apex Class: public class LightningController { @AuraEnabled public static Map < String, String > fetchMapData() { Map < String, String > mapCustomer = new Map < String, String >(); mapCustomer.put('Sample', 'Value'); mapCustomer.put('Sample1'...


16

Don't use Map, just use a normal Object. Here's a demonstration: Apex: public class LightningMap { @AuraEnabled public static void doMap(Map<String, Object> values) { System.debug(values); } } Lightning Controller: ({ doInit: function(component, event, helper) { var action = component.get("c.doMap"); action....


16

The difference is how many times equals will be called (and thus, your performance). As an example, let's take a look at the following class: public class KeyTrial { public static Integer eCounter = 0, hCounter = 0; Integer value; public KeyTrial(Integer val) { value = val; } public Boolean equals(Object o) { eCounter++; ...


16

containsKey and get have the same performance characteristics. The majority of the CPU time used will be within the hashCode and equals methods for the objects used as keys. Poorly designed keys will have poor performance characteristics, particularly when you're Using Custom Types in Map Keys and Sets. In practice, I've found that the majority of the time, ...


15

I think I've figured it out. In java, the hashCode for an enum is not consistent across different executions. My Map is being initialized in the Batchable start() (with Database.Stateful). Then I try to access the map in Batchable execute(). Behind the scenes, salesforce must be running start() & execute() in separate java executions. This means ...


15

Using complex objects as Map keys can have unexpected consequences. In your example, the insert causes the Id of the key Account to be updated so the hashCode and equals methods of the Account produce different results after that. But the Map was setup with the original hashCode and equals results. Effectively you have modified the key and that has broken ...


14

List <Map<String, Integer>> a = new List <Map<String, Integer>> { new Map<String, Integer>{'p1'=>10, 'p2'=>10}, new Map<String, Integer>{'p1'=>20, 'p2'=>20} };


14

In your above example as per doc , Map's remove method takes in only one key as argument and returns a value as return type. you cannot pass a list of strings to the remove method, though I tried something like below based on java's removeall ( undocumented in salesforce map methods ) https://stackoverflow.com/questions/17675804/remove-multiple-keys-from-...


14

Your best bet is to write a wrapper for this. public class AddressWrapper implements Comparable { public Address address; public Integer counter; public AddressWrapper(Address address, Integer counter) { this.address = address; this.counter = counter; } public Integer compareTo(Object other) { return counter-((...


12

I've come across a similar issue before in Using an sObject as a Map key. From Map Considerations: Uniqueness of map keys of user-defined types is determined by the equals and hashCode methods, which you provide in your classes. Uniqueness of keys of all other non-primitive types, such as sObject keys, is determined by comparing the objects’ field values....


12

I wasn't satisfied with the accepted answer, specifically relating to the VisualForce aspect of it, so I performed some additional testing on this critical fix with regard to VF. What I learned is that when a VF iterator (apex:pageBlockTable, apex:repeat, etc.) is used against a Map, one of its undescribed actions is to sort the keys. This completely ...


11

It took 2 months, but this is the "final" answer we got from Support on this topic. Note that the investigation by Tier 3 resulted in this Known Issue being filed which was ultimately the cause for our documented behavior (i.e. by setting a log filter override on a class with a hashCode()/equals() implementation, it effectively disabled hashCode() from being ...


11

Your key in the map is of type Id, so your first for loop should be on Id: for (Id recordId : quotes.keySet()) {} Then your value for each of the keys (IDs) is a list of quotes, meaning the second for loop will be on the Quote object: for (Id recordId : quotes.keySet()) { for (Quote quoteRecord : quotes.get(recordId)) { // do something ...


11

Sfdcfox explains a great reason to use this, but at a more abstract level the reason it's supported it because maps can have any type as a key. In a model where custom classes, or any other type, can be used as keys there seems little reason to make a special case for forbidding SObjects. Using an apex class as a map key has equally odd behavior (without ...


11

You begin your question with: I have a List. 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 answer to the the ...


11

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<...


11

There is a nested limit of 7 collections. If you attempt to go beyond this, you'll get an error: Nested type exceeds maximum level: 8 First question: Is this even possible? Am I exceeding any limits with a Map like this? I have looked over documentation and can't find anything regarding nested map limits. I know it's in the documentation[citation ...


11

Here how you can achieve it. map<string, object> mapToSerialize = new map<string, object>(); mapToSerialize.put('type', 'TEST'); //add you subtype like this mapToSerialize.put('subtypes', new list<string>{'TEST'}); string jsonstring = JSON.serialize(mapToSerialize);


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