Retrieve all values from HashMap keys in an ArrayList Java

前端 未结 9 1467
野性不改
野性不改 2021-01-31 14:21

Good day, this is kind of confusing me now(brain freeze!) and seem to be missing something. Have an ArrayList which i populate with a HashMap. now i put in my HashMap and arrayl

9条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-31 14:56

    This is incredibly old, but I stumbled across it trying to find an answer to a different question.

    my question is how do you get the values from both map keys in the arraylist?

    for (String key : map.keyset()) {
      list.add(key + "|" + map.get(key));
    }
    

    the Map size always return a value of 2, which is just the elements

    I think you may be confused by the functionality of HashMap. HashMap only allows 1 to 1 relationships in the map.

    For example if you have:

    String TAG_FOO = "FOO";
    String TAG_BAR = "BAR";
    

    and attempt to do something like this:

    ArrayList bars = ArrayList<>("bar","Bar","bAr","baR");
    HashMap map = new HashMap<>();
    for (String bar : bars) {
      map.put(TAG_BAR, bar);
    }
    

    This code will end up setting the key entry "BAR" to be associated with the final item in the list bars.

    In your example you seem to be confused that there are only two items, yet you only have two keys recorded which leads me to believe that you've simply overwritten the each key's field multiple times.

提交回复
热议问题