58

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 arraylist.

 Map.put(DATE, value1);
 Map.put(VALUE, value2);

 arraylist.put(Map);

Since am parsing a JSON, the arraylist increases in significant size. now my question is how do you get the values from both map keys in the arraylist? i have tried this

  if(!list.isEmpty()){   // list is an ArrayList

            for(int k = 0; k < list.size(); k++){
                map = (HashMap)list.get(k);
            }

        }

        Log.d(TAG, "map size is" + map.size());

        String [] keys = new String[map.size()];
        String [] date_value = new String[map.size()];

        String [] value_values = new String[map.size()];

        int i = 0;
        Set entries = map.entrySet();
        Iterator iterator = entries.iterator();

        while(iterator.hasNext()){

            Map.Entry mapping = (Map.Entry)iterator.next();
            keys[i] = mapping.getKey().toString(); 
            date_value[i] = map.get(keys[i]);

            if(keys[i].equals(DATE)){
                date_value[i] = map.get(keys[i]);

            } else if(keys[i].equals(VALUE)){
                value_values[i] = map.get(keys[i]);
            }

                   i++;
                 }

But i can't seem to get all the values. the Map size always return a value of 2, which is just the elements. how can i get all the values from the Map keys in the ArrayList? Thanks

1
  • if you are wanting the keys from both maps, you will need to actually GET the keys from both maps. your code just gets the keys from the last map in the list. Commented Oct 18, 2012 at 17:27

9 Answers 9

96

Why do you want to re-invent the wheel, when you already have something to do your work. Map.keySet() method gives you a Set of all the keys in the Map.

Map<String, Integer> map = new HashMap<String, Integer>();

for (String key: map.keySet()) {
    System.out.println("key : " + key);
    System.out.println("value : " + map.get(key));
}

Also, your 1st for-loop looks odd to me: -

   for(int k = 0; k < list.size(); k++){
            map = (HashMap)list.get(k);
   }

You are iterating over your list, and assigning each element to the same reference - map, which will overwrite all the previous values.. All you will be having is the last map in your list.

EDIT: -

You can also use entrySet if you want both key and value for your map. That would be better bet for you: -

    Map<String, Integer> map = new HashMap<String, Integer>();

    for(Entry<String, Integer> entry: map.entrySet()) {
        System.out.println(entry.getKey());
        System.out.println(entry.getValue());
    }

P.S.: -
Your code looks jumbled to me. I would suggest, keep that code aside, and think about your design one more time. For now, as the code stands, it is very difficult to understand what its trying to do.

Sign up to request clarification or add additional context in comments.

3 Comments

entrySet is a better way to iterate the elements in a map if the code in the loop calls get
@RohitJain sorry for replying so late, didn't have a chance after posting the question. what am trying to do is get all the values from the map. As i said in the post, the Hashmap has 2 keys which is populated through a JSON parsing and then added to an ArrayList. I want to retrieve all the values for the 2 keys in the HashMap, which is inside the ArrayList. Yes, i know the first "for" loop look odd. but i was trying to get all the values in the Arraylist because the Hashmap was returning only a size of 2 values and there are more in the ArrayList.
@RohitJain is better if you show the part that explains the "entrySet" in the upper part of the answer, instead of the part that talks about the "keySet". Just swap the order of the sections.
53

List constructor accepts any data structure that implements Collection interface to be used to build a list.

To get all the keys from a hash map to a list:

Map<String, Integer> map = new HashMap<String, Integer>();
List<String> keys = new ArrayList<>(map.keySet());

To get all the values from a hash map to a list:

Map<String, Integer> map = new HashMap<String, Integer>();
List<Integer> values = new ArrayList<>(map.values());

1 Comment

This is the best answer I saw for this question! Directly to the point.
13

Try it this way...

I am considering the HashMap with key and value of type String, HashMap<String,String>

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

hmap.put("key1","Val1");
hmap.put("key2","Val2");

ArrayList<String> arList = new ArrayList<String>();

for(Map.Entry<String,String> map : hmap.entrySet()){

     arList.add(map.getValue());

}

6 Comments

Yeah thats fine now. But why are you adding all your map values to a list? Is it really neede? I think no. Anytime you want a value, you can get it from the Map itself.. For the time being, it is very unclear, what OP wants to do.
@RohitJain I have added the value in the ArrayList as the OP wanted it this way..and thats what the heading of the question says....
@KumarVivekMitra.. Yeah it is correct according to what OP wants, but as this is not correct way to code, you can better add some suggestion. Just for improvement of this post I'm telling. :)
@RohitJain i can, but then we should know what the programmer wants to do with that data..as its not very clear to me that what he wants to do with that data...i am not suggesting anything for now...
@KumarVivekMitra.. Hmm. Yeah that part is also right. Cheers :)
|
2

Create an ArrayList of String type to hold the values of the map. In its constructor call the method values() of the Map class.

Map <String, Object> map;
List<Object> list = new ArrayList<Object>(map.values());

Comments

1

Put i++ somewhere at the end of your loop.

In the above code, the 0 position of the array is overwritten because i is not incremented in each loop.

FYI: the below is doing a redundant search:

if(keys[i].equals(DATE)){                 
   date_value[i] = map.get(keys[i]);              
} else if(keys[i].equals(VALUE)){              
   value_values[i] = map.get(keys[i]);             
} 

replace with

if(keys[i].equals(DATE)){                 
   date_value[i] = mapping.getValue();
} else if(keys[i].equals(VALUE)){              
   value_values[i] = mapping.getValue()
} 

Another issue is that you are using i for date_value and value_values. This is not valid unless you intend to have null values in your array.

4 Comments

Downvoter care to comment? in the above code, the 0 position of the array is overwritten because i is not incremented.
he didn't post code where i is declared. if it's in a for-loop, it's probably already being incremented. you don't know what is going on with 'i' because he hasn't posted anything about 'i'.
@toadzky recheck the post please. Look for int i = 0;. He DID post the code where i is declared.
@JohnB sorry for my late response. But i had that Value of i incremented. i didn't reallise i did not copy it in. Will edit my code now.
1

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<String> bars = ArrayList<>("bar","Bar","bAr","baR");
HashMap<String,String> 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.

Comments

0

Suppose I have Hashmap with key datatype as KeyDataType and value datatype as ValueDataType

HashMap<KeyDataType,ValueDataType> list;

Add all items you needed to it. Now you can retrive all hashmap keys to a list by.

KeyDataType[] mKeys;
mKeys=list.keySet().toArray(new KeyDataType[list.size()]);

So, now you got your all keys in an array mkeys[]

you can now retrieve any value by calling

 list.get(mkeys[position]);

Comments

0

Java 8 solution for produce string like "key1: value1,key2: value2"

private static String hashMapToString(HashMap<String, String> hashMap) {

    return hashMap.keySet().stream()
            .map((key) -> key + ": " + hashMap.get(key))
            .collect(Collectors.joining(","));

}

and produce a list simple collect as list

private static List<String> hashMapToList(HashMap<String, String> hashMap) {

    return hashMap.keySet().stream()
            .map((key) -> key + ": " + hashMap.get(key))
            .collect(Collectors.toList());

}

Comments

-1

It has method to find all values from map:

Map<K, V> map=getMapObjectFromXyz();
Collection<V> vs= map.values();
     

Iterate over vs to do some operation

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.