Wednesday, October 13, 2010

Remove duplicates in a list using Velocity code only

Updates: 25/10/2010. Thanks to Christopher F. Falzone in the post Compound relationship query for a better way to create an empty map.

In dotCMS, I faced a situation where I had a list in Velocity code that contained duplicates. It contained duplicates because I had to traverse a transitive relationship to build a list of objects related to some source object through two separate relationships.

Here is how I removed the duplicates - via a map.

## Remove duplicates.
#set($publishersMap = $contents.getEmptyMap()) ## Make a map to remove dupes.
#foreach($publisher in $publishers)
   #set($dontOutput = $publishersMap.put("$publisher.name", $publisher))
#end
#set($dontOutput = $publishers.clear())
#set($dontOutput = $publishers.addAll($publishersMap.values()))

## Sort.
#set($list = $sorter.sort($publishers, "name"))

Essentially, I am adding all elements from the list to a map (because a map ignores duplicates). Then I clear the original list and add all the elements (values, not keys or entries) back to the original list.

My dotCMS notes.