如何使用Apache Velocity从列表中删除重复元素

12

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

例如,posts 包含重复元素。

#foreach ($p in $posts)
  $p.name //will be unique
#end

我想使用velocity去除重复项,

任何帮助将不胜感激。


3
这些问题应该在Java端解决,Velocity的设计并不适用于构建数据结构。 - serg
4个回答

11

这是可能的,根据您的velocity版本,这应该可以工作。比上面的答案更简洁。

#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

2
甚至更简单:#if( ! $uniquePosts.contains($post.name) && $uniquePosts.add($post.name)) #end - Datz

5

为了证明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

1
使用更新版本更加容易,因为您可以在列表上使用“包含”方法。因此,您只需使用单个foreach循环并将所有未包含的对象添加到列表中,或者甚至可以使用速度图类型并将元素保存为键;-) - Falco

1

在Velocity中你不能这样做。你必须提供一个不包含重复元素的模型。最简单的方法是使用new HashSet<Post>(postsList) - 这将消除重复项(基于equals(..)方法)

如果你真的无法传递正确的模型,你可以尝试定义一个自定义工具,它接受一个列表并返回一个集合,但这并不容易。


0

除了Velocity不支持之外,从架构角度来看,你想要的根本没有意义。 "去重"部分是某种逻辑,需要在正确的位置处理。视图不是做这件事的正确地方。因此,您应该尽一切可能在Java中完成它,甚至会很高兴它在Velocity中不可能。

即使您的角色不允许更改Java代码,仍必须在Java中解决此问题。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接