速度打印值及其键

时间:2014-09-08 11:50:06

标签: java map hashmap key velocity

我知道这是一个非常初学者的问题,但我别无选择:-)我需要在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());
    }

1 个答案:

答案 0 :(得分:2)

最后我已经解决了。这是我的解决方案:

#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
相关问题