You need to sign in to do that
Don't have an account?
mobile 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 ?
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
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))
If none of the answers helped you significantly, please post the solution. You may also mark your solution as the best answer.