12

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

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
imby
  • 121
  • 1
  • 3
  • 3
    Such things should be solved on java side, Velocity wasn't designed to construct data structures. – serg Sep 01 '11 at 21:19

4 Answers4

11

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
Bren1818
  • 2,612
  • 1
  • 23
  • 28
  • 2
    and even simpler: `#if( ! $uniquePosts.contains($post.name) && $uniquePosts.add($post.name)) #end` – Datz Oct 07 '20 at 07:54
5

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
serg
  • 109,619
  • 77
  • 317
  • 330
  • 1
    It is even easier with newer versions, since you can use the method 'contains' on the list. so you can just use a single foreach loop and add all objects to a list, which are not already contained, or you can even use the velocit map-type and save the elements as keys ;-) – Falco Mar 19 '14 at 12:38
1

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.

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
0

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.

Marius Burz
  • 4,555
  • 2
  • 18
  • 28