Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove duplicate elements from a list using apache velocity

Tags:

java

velocity

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

like image 886
imby Avatar asked Sep 01 '11 21:09

imby


2 Answers

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
like image 125
Bren1818 Avatar answered Nov 01 '22 15:11

Bren1818


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
like image 5
serg Avatar answered Nov 01 '22 14:11

serg