Admin User     Feb,08 2017

List Common and List Compare in Coldfusion

If you want to intersect between two list, look at the solution given below :

 <cffunction name="listCommon" output="false" returnType="string"><cfargument name="list1" type="string" required="true" /><cfargument name="list2" type="string" required="true" /><cfset var list1Array = ListToArray(arguments.List1) /><cfset var list2Array = ListToArray(arguments.List2) /><cfset list1Array.retainAll(list2Array) /><!--- Return in list format ---><cfreturn ArrayToList(list1Array) /></cffunction> 

Above listCommon is the user-defined function which returns intersection between two list. In this function first of all, Convert the two list into Array by using the ListToArray function. Then by using the retainAll - which Retains only common array elements of list1Array and list1Array. and lastly convert list1Array to list and it will give intersection of your both list.

Similarly, suppose you have to get the list of elements which are in list1 but not in list2 then look at the another ListCompare function below :

<cffunction name="listCompare" output="false" returnType="string"><cfargument name="list1" type="string" required="true" /><cfargument name="list2" type="string" required="true" /><cfset var list1Array = ListToArray(arguments.List1) /><cfset var list2Array = ListToArray(arguments.List2) /><cfset list1Array.removeAll(list2Array) /><!--- Return in list format ---><cfreturn ArrayToList(list1Array) /></cffunction> 

Here removeAll - Removes all the elements of list1Array collection that are also contained in the list2Array collection.

Let's look at the following Example:

<cfset list1 = "1,2,3,4,5"><cfset list2 = "1,4,5,6,7"><cfoutput>List1 :#list1#<br/>List2 :#list2#<br />ListCommon :#listCommon(list1,list2)#<br />ListCompare :#listCompare(list1,list2)#</cfoutput>

The output of above example is :

List1 :1,2,3,4,5List2 :1,4,5,6,7ListCommon :1,4,5ListCompare :2,3