【问题标题】:Velocity print values and their keys速度打印值及其键
【发布时间】:2014-11-01 15:13:34
【问题描述】:

我知道这是一个真正的初学者问题,但我别无选择 :-) 我需要在 Velocity 中编写一个程序,该程序将采用 Map 并写入所有值及其键(不是键及其值!!!) - 每个值都允许记录在更多键下。

如果你能做到,请帮助我,我会感激每一个答案:-) 非常感谢!

在java中是这样的:

    HashMap<String, String> map = new HashMap<String, String>();
    map.put("key1", "val1");
    map.put("key2", "val1");
    map.put("key3", "val2");
    map.put("key4", "val1");

    HashMap<String, ArrayList<String>> hmap = new HashMap<String, ArrayList<String>>();

    for (Entry<String, String> item : map.entrySet()) {
        String val = item.getValue();
        if (!hmap.containsKey(val)) {
            hmap.put(val, new ArrayList<String>());
            hmap.get(val).add(item.getKey());
        } else {
            hmap.get(val).add(item.getKey());
        }
    }

    for (Entry<String, ArrayList<String>> item : hmap.entrySet()) {
        System.out.println(item.getKey() + " " + item.getValue());
    }

【问题讨论】:

    标签: java map hashmap key velocity


    【解决方案1】:

    终于解决了。这是我的解决方案:

    #set($valToKey = {})
    $!valToKey.put("aaa", ["bbb", "ccc"])
    $!valToKey.get("aaa").add("ddd")
    
    ## fill valToKey map
    #foreach($item in $tmp.entrySet())
        #foreach($value in $item.value)
            #if($valToKey.containsKey($value))
                $!valToKey.get($value).add($item.key) ## use of dummy to prevent printing 'true'
            #else
                $!valToKey.put($value, [$item.key])
            #end
        #end
    #end
    
    ## print valToKey map
    #foreach($item in $valToKey.entrySet())
    
        $item.key
        ## print all values according to key
        #foreach($value in $item.value)
            $indent  -> $value
        #end
    #end
    

    【讨论】:

    • 你用什么假人来阻止 true 打印?
    • @user2900150 对不起,该评论应该被删除:-)
    猜你喜欢
    • 1970-01-01
    • 2013-04-30
    • 1970-01-01
    • 2012-09-27
    • 1970-01-01
    • 2017-02-05
    • 2013-05-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多