I have the following ArrayList
ArrayList<HashMap<String, String>> list;
HashMap<String, String> map;
with the following values inside:
list[0] = map.put("key_0", value_0);
list[1] = map.put("key_1", value_1);
list[2] = map.put("key_2", value_2);
I would like to parse the list array and get the value of the key at a specific position.
You can get the particular map from the ArrayList> by using get() method. for example,
map = list.get(index);
And to get key of that map, you can do:
String key = map.get("key");
FYI, this is the feasible solution, i dont know why you are using key name like key_0, key_1, key_2...and so on.
Related
I created multi dimensional array using hashmap. How to read value of 2nd array using key which is a String. I read on other articles it say using keyset and iterator but never show how to read specific value using String key.
HashMap<Integer, HashMap<String, String>> myMap = new HashMap<Integer, HashMap<String, String>>();
Example array (structure only):
myMap[1]["title"] = "test";
I can read this:
myMap.get(1);
But i cant read this:
myMap.get(1).get("title");
I also tried but failed:
HashMap<String, String> subHash = myMap.get(position);
subHash.get("title");
I have written this:
HashMap<String, String> map1 = new HashMap<String, String>();
Map<String, ArrayList<String>> map2 = new HashMap<String, ArrayList<String>>();
i am trying to allow more then 1 value for each key in a hashmap. so if the first key is '1', i want to allow '1' to be paired with values '2' and '3'.
so it be like:
1 --> 2
|--> 3
but when I do:
map2.put(key, value);
it gives error that says "incompatible types" and it can not be converted to ArrayList and it says the error is at the value part of the line.
If you are using Java 8, you can do this quite easily:
String key = "someKey";
String value1 = "someValue1";
String value2 = "someValue2";
Map<String, List<String>> map2 = new HashMap<>();
map2.computeIfAbsent(key, k -> new ArrayList<>()).add(value1);
map2.computeIfAbsent(key, k -> new ArrayList<>()).add(value2);
System.out.println(map2);
The documentation for Map.computeIfAbsent(...) has pretty much this example.
In map2 you need to add ArrayList (you declared it as Map<String, ArrayList<String>> - the second one is the value type) only, that's why it gives you incompatible types.
You would need to do initialize the key with an ArrayList and add objects to it later:
if (!map2.containsKey(key)) {
map2.put(key, new ArrayList<String>());
}
map2.get(key).add(value);
Or you could use Multimap from guava, then you can just map2.put and it won't overwrite your values there but add to a list.
You are little bit away from what you are trying to do.
Map<String, ArrayList<String>> map2 = new HashMap<String, ArrayList<String>>();
this will allow only String as key and an ArrayList as value. So you have to try something like:
ArrayList<String> value=new ArrayList<String>();
value.add("2");
value.add("3");
map2.put("1", value);
When retrieving you also have to follow ans opposite procedure.
ArrayList<String> valueTemp=map2.get("1");
then you can iterate over this ArrayList to get those values ("2" and "3");
Try like this. //use list or set.. but set avoids duplicates
Map<String, Set<String>> map = new HashMap<>();
Set<String> list = new HashSet<>();
// add value to the map
Boolean b = map.containsKey(key);
if (b) {
map.get(key).addAll(list);
} else
map.put(key, list);
}
You can not add different values in same key in Map. Map is override the value in that key. You can do like this way.
Map<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
ArrayList<String> list=new ArrayList<String>();
list.add("2");
list.add("3");
map.put("1", list);
first add value in array list then put into map.
It is all because standard Map implementations in java stores only single pairs (oneKey, oneValue). The only way to store multiple values for a particular key in a java standard Map is to store "collection" as value, then you need to access this collection (from Map) by key, and then use this collection "value" as regular collection, in your example as ArrayList. So you do not put something directly by map.put (except from creating the empty collection), instead you take the whole collection by key and use this collection.
You need something like Multimap, for example:
public class Multimap<T,S> {
Map<T, ArrayList<S>> map2 = new HashMap<T, ArrayList<S>>();
public void add(T key, S value) {
ArrayList<T> currentValuesForGivenKey = get(key);
if (currentValuesForGivenKey == null) {
currentValuesForGivenKey = new ArrayList<T>();
map2.get(key, currentValuesForGivenKey);
}
currentValuesForGivenKey.add(value);
}
public ArrayList<S> get(T key) {
ArrayList<String> currentValuesForGivenKey = map2.get(key);
if (currentValuesForGivenKey == null) {
currentValuesForGivenKey = new ArrayList<S>();
map2.get(key, currentValuesForGivenKey);
}
return currentValuesForGivenKey;
}
}
then you can use it like this:
Multimap<String,String> map2 = new Multimap<String,String>();
map2.add("1","2");
map2.add("1","3");
map2.add("1","4");
for (String value: map2.get("1")) {
System.out.println(value);
}
will print:
2
3
4
it gives error that says "incompatible types" and it can not be converted to ArrayList and it says the error is at the value part of the line.
because, it won't automatically convert to ArrayList.
You should add both the values to list and then put that list in map.
I defined a hashmap as follows
HashMap<String, List<String>> hashmap = new HashMap<String, List<String>>();
I can get its content out by doing
Set<Map.Entry<String, List<String>>> keys = hashmap.entrySet();
for (Map.Entry<String,List<String>> entry : hashmap.entrySet()) {
String key = entry.getKey();
List<String> thing = entry.getValue();
System.out.println (key);
System.out.println (thing);
}
However, I would like to know:
How could I retrieve its content to an ordinary string?
Is it possible to access the strings on the fly? (without doing (1)) I mean, the same way you do string[0], etc
Where is the length of the list stored?
Assuming that String key = "str"; exists in the map. You can:
int mapSize = hashmap.size(); // get the map's size
List<String> list = hashmap.get("str"); // get a list for a key
String first = hashmap.get("str").get(0); // get a string in a list
int listSize = hashmap.get("str").size(); // get the size of a list
char ch = hashmap.get("str").get(0).charAt(0); // get a char of a string in a list in the map
Instead of manually getting the set of keys, how about using the keySet() method on the HashMap object from Java?
Use of keySet() looks like:
Set<String> keys = hashmap.keySet();
For the third bullet, see the size() method.
I am trying listItem.indexOf(word.text)==-1 to find the string I want.
Using indexOf function in single ArrayList is working fine. but after I use HashMap combine ArrayList, the indexOf function seems not working.
Any solution? thx!
ArrayList<HashMap<String, Object>> listItem= new ArrayList<HashMap<String,Object>>();
SimpleAdapter mSimpleAdapter = new SimpleAdapter(this,listItem, R.layout.item_main, new String[] {"ItemImage","ItemTitle", "ItemText"},
new int[] {R.id.ItemImage,R.id.ItemTitle,R.id.ItemText});
if(listItem.indexOf(word.text)==-1){
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("ItemImage", R.drawable.speak2);
map.put("ItemTitle", word.text);
map.put("ItemText", temp);
listItem.add(map);
}
I'm assuming that word.text is a String. Therefore you have no reason to expect that listItem.indexOf(word.text) would find it in a List that contains HashMap instances.
It looks like you are storing word.text as one of the values of a HashMap stored in the list. To search for a HashMap in the List that contains this value you have to iterate over all the Maps in the List, and for each Map, iterate over all its values.
Perhaps a better data structure would be HashMap<String,HashMap<String, Object>, where the key is taken from word.text and the value is the HashMap you currently store in the list. This way, you could replace listItem.indexOf(word.text) with mapItem.containsKey(word.text), which is more efficient, and would work.
HashMap<String,HashMap<String, Object>> mapItem= new HashMap<String,HashMap<String,Object>>();
if(!mapItem.containsKey(word.text)){
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("ItemImage", R.drawable.speak2);
map.put("ItemTitle", word.text);
map.put("ItemText", temp);
mapItem.put(word.text, map);
}
Is there anyone who knows how to convert a Map to a List
I found here something like this :
List<Value> list = new ArrayList<Value>(map.values());
But this is going to store just the value of the Map to the List
What I want to do is : copy the Key & the Value to the List
So, do you know how to achieve this ?
This will give you a List of the Map entries:
List<Map.Entry<Key, Value>> list =
new ArrayList<Map.Entry<Key, Value>>(map.entrySet());
FYI, entries have a getKey() and a getValue() method.
One way you can do is Create a List with adding all the keys like :
List list = new ArrayList(map.keySet());
Then add all the values like :
list.addAll(map.values);
And then probably you have to access with index like:
if map size is 10 , you know that you have 20 elements in the list.
So you have to write a logic to access the key-value from the list with proper calculation of index like: size/2 something like that.
I am not sure if that helps what your requirement is.
Both #Bohemian and #dacwe are right. I'd say moreover: in most cases you do not have to create your own list. Just use map.entrySet(). It returns Set, but Set is just a Collection that allows iterating over its elements. Iterating is enough in 95% of cases.
Try storing the Map.Entrys of the map:
new ArrayList<Entry<Key, Value>>(map.entrySet());
Example:
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("Hello", 0);
map.put("World!", 1);
ArrayList<Entry<String, Integer>> list =
new ArrayList<Entry<String, Integer>>(map.entrySet());
System.out.println(list.get(0).getKey() + " -> " + list.get(0).getValue());
}