Getting the Intersection of 2 Arrays with ColdFusion

8 Apr 13 - Coldfusion, Railo - Janusz Buda - 2 Comments

Just a simple post while working on some ColdFusion and one that many may know, but it is new for me! I had a situation where I had two arrays and needed to get the values that existed in both, and return a new array based on the intersection.

The initial method that came to mind was :

The resultant array from the dump is:


This works fine and there is no issue with it but the nested loops does look ugly. Having been working on some Java in recent weeks with another project, I decided to see if there was any Java functions that could be used to get the same result. Some googling later, I found the retainAll function that pretty much enables the same function.

Again, the result that is dumped out:



Either option is completely valid and provides the same result. My preferred option in this case would be the 2nd one. The ability to remove the nested loop and reduce the amount of lines of codes is a definite win for me, and show the power of ColdFusion by being able to utilise the underlying Java API.


  • Mark Gregory April 8, 2013 at 2:07 pm

    I didn’t know this one. Nice!
    Nested loops always make me feel a little dirty.

  • Aaron Cox April 8, 2013 at 2:23 pm

    As always, be aware of Java’s case-sensitivity. Otherwise, Java’s Collection.retainAll() and Collection.removeAll() are fantastic shortcuts.

Leave a Comment