如果密钥在HashMap中匹配,则打印值

时间:2017-03-02 10:08:26

标签: java hashmap

如果密钥匹配,如何打印两个不同HashMaps的值?

<FrameLayout>
  <FrameLayout/>
  <FrameLayout/>
  ...(almost 100 for example)
<FrameLayout/>

我希望结果看起来像这样:

HashMap<String, String> color = new HashMap<String, String>();
HashMap<String, String> fruits = new HashMap<String, String>();

color.put("11", "red");
color.put("14", "blue");
color.put("26", "green");
fruits.put("26", "banana");
fruits.put("11", "apple");
fruits.put("14", "melon");

我目前的尝试

"11 : red apple"
"14 : blue melon"
"26 : green banana"

3 个答案:

答案 0 :(得分:1)

使用流并将其收集到新地图

Map<String, String> map = color.entrySet().stream()
    .collect(Collectors.toMap(Map.Entry::getKey,
        e -> color.get(e.getKey()) + " " + fruits.get(e.getKey())));
System.out.println(map); // {11=red apple, 14=blue melon, 26=green banana}

答案 1 :(得分:1)

试试这个:

public static void main(String[] args) {

    HashMap<String, String> color = new HashMap<String, String>();
    HashMap<String, String> fruits = new HashMap<String, String>();

    color.put("11", "red");
    color.put("14", "blue");
    color.put("26", "green");
    fruits.put("26", "banana");
    fruits.put("11", "apple");
    fruits.put("14", "melon");
    fruits.put("15", "test");

    Set<String> colorKeys = color.keySet();
    Set<String> fruitsKeys = fruits.keySet();

    colorKeys.retainAll(fruitsKeys); //// colorKeys now contains only elements in both sets

    for (String key : colorKeys) {

        String sColor = color.get(key);
        String sFruit = fruits.get(key);

        System.out.println(String.format("%s : [%s  %s]" , key, sColor, sFruit));

    }
}

输出:

11 : [red  apple]
14 : [blue  melon]
26 : [green  banana]

答案 2 :(得分:0)

我希望这个功能有效

public void get(Map<String, String> map1, Map<String, String> map2){
    for(Map.Entry m:map1.entrySet())
    {
        for(Map.Entry n:map2.entrySet())
        {
            if(m.getKey()==n.getKey())
            {
                System.out.println(m.getKey()+" : "+m.getValue()+" , "+n.getValue());
            }
        }
    }
}