In my last post about combining two lists, Geoffrey asked:

Is there an easy way in CF to find an intersection between two lists? It seems like listFind and listContains can find an element in a list, but what if you wanted to find if any element from list A were in list B?

Like most things in ColdFusion, there is not a single method for finding the intersection, or shared values, between two lists. Geoffrey already mentioned two built-in functions that are useful for comparing list values.

First, let's set up two lists of values:

view plain print about
1<cfset variables.aList = "1,2,3,5,8,13">
2<cfset variables.bList = "1,3,4,7,11,18">

By using a loop and the listFind function, we can generate a list of values shared between the two lists:

view plain print about
1<cfset variables.finalList = "">
2
3<!--- Examine each element in the first list and see if it exists in the second. --->
4<cfloop list="#variables.aList#" index="itm">
5    <cfif listFind(variables.bList, itm)>
6        <cfset variables.finalList = listAppend(variables.finalList, itm)>
7    </cfif>
8</cfloop>

The resulting list is:

view plain print about
11,3

Simple and effective, but there is another way.

Since ColdFusion is, ultimately, a Java application, we can use the underlying Java API to manipulate many CF variables, as demonstrated by Rupesh Kumar.

Again, let's start with our two lists:

view plain print about
1<cfset variables.aList = "1,2,3,5,8,13">
2<cfset variables.bList = "1,3,4,7,11,18">

Since ColdFusion lists are just strings (java.lang.String) our options are very limited. But we can easily covert them to arrays, which are implemented as Java lists (java.util.List), which gives us access to a rich API:

view plain print about
1<cfset variables.aList = listToArray("1,2,3,5,8,13")>
2<cfset variables.bList = listToArray("1,3,4,7,11,18")>

One of the methods available to Java lists is retainAll which "Retains only the elements in this list that are contained in the specified collection." In other words, we can remove any items from the first list that do not exist in the second:

view plain print about
1<!--- Create a deep copy of the first list to keep it intact. --->
2<cfset variables.finalList = duplicate(variables.aList)>
3<!--- Remove any elements from the first list that do not exist in the second. --->
4<cfset variables.finalList.retainAll(variables.bList)>
5<cfset variables.finalList = arrayToList(variables.finalList)>

The result is the intersection between the two original lists:

view plain print about
11,3