I have a list with duplicate elements,I need to use velocity
For Example, posts contains duplicate elements
#foreach ($p in $posts)
$p.name //will be unique
#end
I want to remove the duplicate using velocity,
Any help would be appreciated
I have a list with duplicate elements,I need to use velocity
For Example, posts contains duplicate elements
#foreach ($p in $posts)
$p.name //will be unique
#end
I want to remove the duplicate using velocity,
Any help would be appreciated
This is possible, and this should work depending on your version of velocity. A bit more concise than the answer above.
#set($uniquePosts = [])
#foreach($post in $posts)
#if( ! $uniquePosts.contains( $post.name ) )
#if( $uniquePosts.add($post.name) ) #end
##note the if above is to trap a "true" return - may not be required
$post.name
#end
#end
Just for the sake of argument because others said it is not possible with Velocity, I wanted to show that it is actually possible with Velocity, but still not recommended.
For those who are interested how it could be done:
#set($uniquePosts = [])
#foreach($post in $posts)
#set($exists = false)
#foreach($uniquePost in $uniquePosts)
#if($uniquePost.name == $post.name)
#set($exists = true)
#break
#end
#end
#if(!$exists)
#set($added = $uniquePosts.add($post))
#end
#set($posts = $uniquePosts)
#end
Unique list:
#foreach($post in $posts)
$post.name
#end
You can't do that in velocity. You have to provide a model that contains no duplicates. The easiest way is to use new HashSet<Post>(postsList)
- this will eliminate the duplicates (based on the equals(..)
method)
If you really can't pass the proper model, you can try to define a custom tool that takes a list and returns a set, but that wouldn't be easy.
Aside from not being possible in Velocity, from an architectural point of view what you want doesn't make sense at all. The "removing duplicates" part is some sort of a logic and this needs to be taken care of in the proper place. A view is not the right place for doing that. So you should do it by all means in Java and even be happy it's not possible in Velocity.
Even if your role does not allow for changing Java code, this must still be solved in Java.