如何使用apache velocity从列表中删除重复的元素

imb*_*mby 7 java velocity

我有一个包含重复元素的列表,我需要使用velocity

例如,帖子包含重复的元素

#foreach ($p in $posts)
  $p.name //will be unique
#end
Run Code Online (Sandbox Code Playgroud)

我想使用velocity删除副本,

任何帮助,将不胜感激

ser*_*erg 5

仅仅是为了争论,因为其他人说Velocity是不可能的,我想表明它实际上可以用Velocity,但仍然不推荐.

对于那些有兴趣如何做的人:

#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
Run Code Online (Sandbox Code Playgroud)


Bre*_*818 5

这是可能的,并且这应该根据您的力度版本而起作用。比上面的答案更简洁。

#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
Run Code Online (Sandbox Code Playgroud)

  • 甚至更简单:`#if(!$uniquePosts.contains($post.name) && $uniquePosts.add($post.name)) #end` (2认同)

Boz*_*zho 1

你无法以速度做到这一点。您必须提供一个不包含重复项的模型。最简单的方法是使用new HashSet<Post>(postsList)- 这将消除重复项(基于equals(..)方法)

如果您确实无法通过正确的模型,您可以尝试定义一个自定义工具,该工具接受一个列表并返回一个集合,但这并不容易。