The problem is that the Apex list add
method returns a Boolean rather than the list itself, so it isn't possible to append to the list and initialize in one line.
You can save one line of code like this using the map initialization syntax:
Configuration__c c = ...
List<Configuration__c> tempList = serviceTypeFieldsMap.get(detail.ServiceType__c);
tempList.add(c);
Map<String, List<Configuration__c>> mapConfig = new Map<String, List<Configuration__c>>{c.ServiceType__c => tempList};
In the general case you can construct and initialise collections in a single line like this:
List<String> l = new List<String>{'a', 'b', 'c'};
Set<String> s = new Set<String>{'a', 'b', 'c'};
Map<String, String> m = new Map<String, String>{'a' => 'x', 'b' => 'y', 'c' => 'z'};
including nested combinations such as this one:
Map<String, List<String>> m = new Map<String, List<String>>{
'a' => new List<String>{'p', 'q', 'r'},
'b' => new List<String>{'s', 't', 'u'}
};
PS
Based on your comment, if both mapConfig
and serviceTypeFieldsMap
are defined at the class level, perhaps the best you can do is move the code to a method:
private void someMethod() {
...
if (...) addToConfig(detail1.ServiceType__c, c1);
...
if (...) addToConfig(detail2.ServiceType__c, c2);
...
if (...) addToConfig(detail3.ServiceType__c, c3);
...
}
private void addToConfig(String key, Configuration__c c) {
List<Configuration__c> tempList = serviceTypeFieldsMap.get(key);
tempList.add(c);
mapConfig.put(key, tempList);
}