Best way to create a hashmap of arraylist
You don't need to re-add the ArrayList back to your Map. If the ArrayList already exists then just add your value to it.
An improved implementation might look like:
Map<String, Collection<String>> map = new HashMap<String, Collection<String>>();
while processing each line:
String user = user field from line
String value = value field from line
Collection<String> values = map.get(user);
if (values==null) {
values = new ArrayList<String>();
map.put(user, values)
}
values.add(value);
Follow-up April 2014 - I wrote the original answer back in 2009 when my knowledge of Google Guava was limited. In light of all that Google Guava does, I now recommend using its Multimap
instead of reinvent it.
Multimap<String, String> values = HashMultimap.create();
values.put("user1", "value1");
values.put("user2", "value2");
values.put("user3", "value3");
values.put("user1", "value4");
System.out.println(values.get("user1"));
System.out.println(values.get("user2"));
System.out.println(values.get("user3"));
Outputs:
[value4, value1]
[value2]
[value3]
How to fill a hashmap with an arraylist?
You should use Map.computeIfAbsent
:
intMap.computeIfAbsent(someKey, k -> new ArrayList<>()).add(someValue);
For example, to have these mappings:
1 -> [2, 3]
5 -> [8]
6 -> [7, 9, 4]
You could do it this way:
intMap.computeIfAbsent(1, k -> new ArrayList<>()).add(2);
intMap.computeIfAbsent(1, k -> new ArrayList<>()).add(3);
intMap.computeIfAbsent(5, k -> new ArrayList<>()).add(8);
intMap.computeIfAbsent(6, k -> new ArrayList<>()).add(7);
intMap.computeIfAbsent(6, k -> new ArrayList<>()).add(9);
intMap.computeIfAbsent(6, k -> new ArrayList<>()).add(4);
EDIT:
Map.computeIfAbsent
is equivalent to this code:
List<Integer> list = intMap.get(someKey);
if (list == null) {
list = new ArrayList<>();
intMap.put(someKey, list);
}
list.add(someValue);
Java: create a list of HashMaps
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.
HashMap with ArrayList
I believe you're looking for something like this,
List<Object> al = map.get(key);
if (al == null) {
al = new ArrayList<Object>();
map.put(key, al);
}
al.add(value);
Please note that the above uses raw Object
Lists. You should (if possible) pick a proper type, and use it.
Edit
Some prefer the (slightly shorter) form,
if (!map.containsKey(key)) {
map.put(key, new ArrayList<Object>());
}
map.get(key).add(value);
How to add element into ArrayList in HashMap
HashMap<String, ArrayList<Item>> items = new HashMap<String, ArrayList<Item>>();
public synchronized void addToList(String mapKey, Item myItem) {
List<Item> itemsList = items.get(mapKey);
// if list does not exist create it
if(itemsList == null) {
itemsList = new ArrayList<Item>();
itemsList.add(myItem);
items.put(mapKey, itemsList);
} else {
// add if item is not already in list
if(!itemsList.contains(myItem)) itemsList.add(myItem);
}
}
Creating HashMap from ArrayList
First of all, we're making the assumption that both k and v will be of equal length AND that keys will be unique. You may want to surround the mapping with a try/catch block.
HashMap<String, String> map = new HashMap<String, String>();
ArrayList<String>k = receivedIntent.getStringArrayListExtra("keys");
ArrayList<String>v = receivedIntent.getStringArrayListExtra("values");
for(int i = 0; i < k.size(); i++) map.put(k.get(i), v.get(i));
Create and populate HashMapInteger, ArrayListobject
You will need a way to parse your lines into UniversityScore
objects.
Now that you have all the scores, you can add it to your map, according to their year values (may be score but the type doesn't match nor makes practical sense), for example:
for(String line : lines){
String[] vals = line.split(";");
UniversityScore score = new UniversityScore(vals[0],vals[1],Double.parseDouble(vals[2]),Integer.parseInt(vals[3]))
if(scores.containsKey(score.getYear()){ // If the key exists
scores.get(score.getYear()).add(score);
}else{ // If the key doesn't exist, it must be created and added to the map
ArrayList<UniversityScore> newList = new ArrayList<>();
newList.add(score);
scores.put(score.getYear(), newList)
}
}
I noticed your map has an Integer
key which corresponds to the year
property of a score, so I assumed the map's keys are the years and not the scores as you suggested.
I didn't check if the code works, but it should at least give you an idea on how to fill your map.
How can I store HashMapString, ArrayListString inside a list?
Always try to use interface reference in Collection, this adds more flexibility.
What is the problem with the below code?
List<Map<String,List<String>>> list = new ArrayList<Map<String,List<String>>>();//This is the final list you need
Map<String, List<String>> map1 = new HashMap<String, List<String>>();//This is one instance of the map you want to store in the above list.
List<String> arraylist1 = new ArrayList<String>();
arraylist1.add("Text1");//And so on..
map1.put("key1",arraylist1);
//And so on...
list.add(map1);//In this way you can add.
You can easily do it like the above.
java HashMap and ArrayList in one
You could use composition:
public class HashedList<K, V> {
private final List<V> list = new ArrayList<>();
private final Map<K, V> map = new HashMap<>();
protected K getKey(V val);
public void add(V value) {
list.add(value);
map.put(getKey(value), value);
}
public V get(int index) {
return list.get(index);
}
public V get(K key) {
return map.get(key);
}
}
Related Topics
How to Disable 'X-Frame-Options' Response Header in Spring Security
Efficiently Finding the Intersection of a Variable Number of Sets of Strings
How to Iterate Over a Priorityqueue
How to Extract Parameters from a Given Url
Creating Unicode Character from Its Number
Differences Between Runtime/Checked/Unchecked/Error/Exception
Gwt: Timer and Scheduler Classes
Often Big Numbers Become Negative
Why Is It Not Possible to Shadow a Local Variable in a Loop
Postgresql Uuid Supported by Hibernate
Java Key Listener in Commandline
Parsing String to Local Date Doesn't Use Desired Century
Efficient Way to Divide a List into Lists of N Size
Valid Jar Signature for Javafx Projects
Java String.Split() Sometimes Giving Blank Strings
What Are the Date Formats Available in Simpledateformat Class