Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: create a list of HashMaps

Tags:

java

arraylist

I tried to create a list of maps. In the following code, I'm expecting to get

[{start=1,text=ye}, {start=2,text=no}]

however, I only got

[{start=2,text=no}, {start=2,text=no}]

How to avoid overriding the first map? Here is my code:

HashMap mMap = new HashMap();
ArrayList list = new ArrayList();
list.add(new HashMap());
mMap.put("start",1);
mMap.put("text","yes");
list.add(mMap); 
mMap.put("start",2);
mMap.put("text","no");
list.add(mMap); 
System.out.println("Final result: " + list );

thanks!

==========================

As a learner of Java who came from a procedure language background (SAS), I spent quite a few hours learning and experimenting ArrayList, LinkedList, Map, LinkedMap, etc--- I coldn't get it to work. And I don't understand why with my limited knowledge. Now, these following answers are all excellent! They explained very important data structure in Java, at least for me.

THANK YOU ALL!!!!

like image 466
john Avatar asked Nov 04 '10 19:11

john


People also ask

Can we create list of HashMap in Java?

HashMap mMap = new HashMap(); ArrayList list = new ArrayList(); list. add(new HashMap()); mMap. put("start",1); mMap. put("text","yes"); list.

Can you make an ArrayList of HashMaps?

A HashMap contains key-value pairs, there are three ways to convert a HashMap to an ArrayList: Converting the HashMap keys into an ArrayList. Converting the HashMap values into an ArrayList. Converting the HashMap key-value pairs into an ArrayList.

Can we have list of maps in Java?

A Map is an object that maps keys to values or is a collection of attribute-value pairs. The list is an ordered collection of objects and the List can contain duplicate values. The Map has two values (a key and value), while a List only has one value (an element).


2 Answers

Something which is maybe also worth mention it, is that you should define the type of the elements you use in the List, for the HashMap its not possible because you are mixing Integers and Strings.

And another thing is that you should use the List interface as type, so you are able to change the implementation (ArrayList or whatever) in the future.

Here the corrected code:

Map mMap = new HashMap();
List<Map> list = new ArrayList();
like image 115
Prine Avatar answered Oct 14 '22 07:10

Prine


You need to create a new HashMap for every entry, instead of reusing the existing one. This would work:

HashMap mMap = new HashMap();
mMap.put("start",1);
mMap.put("text","yes");
list.add(mMap); 
mMap = new HashMap(); // create a new one!
mMap.put("start",2);
mMap.put("text","no");
list.add(mMap); 

also, you can remove the list.add(new HashMap()); as that adds an empty map to your list that is never populated.

like image 24
Luke Hutteman Avatar answered Oct 14 '22 09:10

Luke Hutteman