Wednesday 23 February 2022

Find duplicate element from a list in Salesforce Apex

How to find duplicate element from a list in Apex

Below are the  ways to find duplicate element:

1. Choose 'Set' instead of 'List' -- It prevents to add duplicate elements in list.

like we have a set of elements {2,1,5,7,6,5}

if we choose 'List':

List<Integer> listData = new List<Integer>{2,1,5,7,6,5};

then Output is : (2, 1, 5, 7, 6, 5)


If we choose 'Set':  :

Set<Integer> listData = new Set<Integer>(2, 1, 5, 7, 6, 5);

then Output is : (2, 1,7, 6, 5) -- Duplicates removed

2. Find duplicates by sorting of list elements : 

List<Integer> listData = new List<Integer>{2,1,5,7,6,5};
listData.sort();  // Sort the data - It sorts in ascending order
System.debug(listData);  // output is - (1, 2, 5, 5, 6, 7)

Integer elementPosition = listData.indexOf('5'); // Now you want to find duplicate of any '5' (you can check for any element) , then first find the index of that element

// below check if data on 'elementPosition' is equals to data on 'elementPosition+1' or 'elementPosition-1' , if found then there is duplicate element in list.

if(listData.get(elementPosition) == listData.get(elementPosition+1) ||                   listData.get(elementPosition) == listData.get(elementPosition+1))
{
    System.debug('Duplicate found')
}



    


0 comments:

Post a Comment

If you have any doubts, please let me know.