function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
mobile vistexmobile vistex 

how to make two fields as a unique key in apex class

hi iam trying to built a list where i want to make to fields as unique . how can i achieve this .  iam trying pair numbers but giving error to me. is any other method is there ?
Best Answer chosen by mobile vistex
JayantJayant
You may concatenate both the fields and put in a set or map.

Suppose abc and xyz are the fields then do this - 

Set<String> uniqueKeys = new Set<String>();

for(Object o : Objects) {
if(uniqueKeys.contains(o.abc + o.xyz)) {
//handle duplicate here, I am just logging
System.debug('Dupe found : ' + o.Id); //combination has already appeared earlier, its a duplicate record
else {
uniqueKeys.add(o.abc + o.xyz); //first time a combination appears, concatenated string would be added to set
}
}

You may also use a map, if you also want to have the record along - 
mapUniqueKeys.put(o.abc + o.xyz, o);

You may use containsKey method on the map to find dupes on Map Keys like - 
if(mapUniqueKeys.containsKey(o.abc + o.xyz))

All Answers

JayantJayant
You may concatenate both the fields and put in a set or map.

Suppose abc and xyz are the fields then do this - 

Set<String> uniqueKeys = new Set<String>();

for(Object o : Objects) {
if(uniqueKeys.contains(o.abc + o.xyz)) {
//handle duplicate here, I am just logging
System.debug('Dupe found : ' + o.Id); //combination has already appeared earlier, its a duplicate record
else {
uniqueKeys.add(o.abc + o.xyz); //first time a combination appears, concatenated string would be added to set
}
}

You may also use a map, if you also want to have the record along - 
mapUniqueKeys.put(o.abc + o.xyz, o);

You may use containsKey method on the map to find dupes on Map Keys like - 
if(mapUniqueKeys.containsKey(o.abc + o.xyz))
This was selected as the best answer
JayantJayant
If this is resolved, please do mark the question as Resolved and the most appropriate/helpful answer as the best answer :).
If none of the answers helped you significantly, please post the solution. You may also mark your solution as the best answer.