Can I have arrays in Hashmaps ?
If so, what's the exact syntax to declare such hashmap ?
thanks
Arrays are objects, too. Even primitive arrays like int[].
Map<String,String[]> map = new HashMap<String,String[]>();
Value? that's fine, an array is an Object.
Key? Not so easy - see here:
Using a byte array as Map key
Yes. Below is an example that uses int [] as values. Example here.
Map<String, int[]> map = new TreeMap<String, int[]>();
HashMap<String, String[]> ab = new HashMap<String, String[]>();
I think you should use ArrayList instead of a primitive array. Becouse of the == comparision done inside of the HashMap class.
So, you could have something like this:
HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
When the map checks if some element (given its key "k") is present in the array it computes its hashcode. If there's some element at that position "k", then a colision may be produced, so it checks if the elements are the same. Something that can have some troubles with primitives arrays.
Related
If I have a HashMap<String,Object> that has three entries that are <String,String> and one that is <String,Integer> is there a way to "cast" this into a HashMap<String,String> easily? Right now I and making a new HashMap and copying all of the values over so that I can convert the Integer during the copying.
Should be able to cast it, but expect an exception when trying to retrieve one of the integers out of the map.
What I think you're asking is to cast the content of the hashmap, in this case the values, so they all come out as strings, and that's not going to happen.
Best solution is to convert the integer into a string when populating the map in the first place.
You can cast the original map, no need to copy:
map.put("intKey", map.get("intKey").toString());
Map<String, String> fixedMap = (Map) map;
It does look like something is wrong with your design though. It would be better to fix the code that shoves the integer into the map to begin with, so that you would not need to deal with this trickery downstream.
Something like this should be easier:
Class<? extends Object> className = obj.getClass();
if (className.getName().contains("String")){
//add the object
}else {
//convert it to String and then add to HashMap
}
If you're using java 8, you can use forEach with BiConsumer.
Take a look in the code below
Map<String, Object> map = new HashMap<>();
map.put("a", "a");
map.put("b", "b");
map.put("1", Integer.valueOf(1));
map.forEach((k, v) -> map.put(k, v.toString()));
After line map.forEach((k, v) -> map.put(k, v.toString())); all values in the map are Strings. Of courste that loop is still there, but you are using a language feature/resource.
One problem that I am facing in my code is that I have a long list of strings that map to different integers. For example, "Apple" maps to 4, "Bat" maps to 7, etc. Is there any ways to create an Array List such that a string is used as the input search element rather than a traditional number? Ie. Array["Apple"] instead of Array[4]
Use an associative data structure for this.
Map<String, Integer> items = new HashMap<>();
items.put("Apple", 4);
items.put("Bat", 7);
items.get("Apple");
items.get("Bat");
ArrayList doesn't have that support. But Hashmaps can solve your usecase. Check that out.
You can use a Map to solve your use case.
Map<String, Integer> fruits = new HashMap<String, Integer>();
Now your fruits Map will have the String as a key and Integer as a value.
To put key-value: fruits.put("Apple", 1)
To get value based on key: fruits.get("Apple")
You will need two data structures for this problem: a Map to associate item names with indices and a List to store the items (e.g. an ArrayList). For example (untested):
// Store the items and a mapping of their indices by name.
List<String> items = new ArrayList<String>();
Map<String, Integer> itemIndices = new HashMap<String, Integer>();
// Add the item to both data structures.
itemIndices.put("Apple", 4);
items.add("Apple", 4);
// Now you can fetch them by name.
items.get(itemIndices.get("Apple")); // => "Apple"
Of course, you can use a Map<String,Integer> directly, with no need for the List...
Let's say I have arraylist of Hashmap,
and Hashmap contain some keys and values
Arraylist d = [{key1=1,key2=2},{key1=1,key3=3}]
I want to remove hashmap that does not contain certain key.
for example, I want to remove hashmap that does not have key2.
result should be:
d= [{key=1,key2=2}]
How do I approach this?
If source is
List<Map<String, Integer>> list;
You can filter it that way:
List<Map<String, Integer>> newList =
list.stream().filter(m -> m.containsKey("key2")).collect(Collectors.toList());
I have to maintain the list of indexes for each of the key value in HashMap.
So i declared HashMap as
HashMap<Integer,HashSet<Integer> hset = new HashSet<Integer>()> hm = new HashMap<Integer,HashSet<Integer> hset = new HashSet<Integer>()>();
but the above declaration seems to be not correct.
So i declared it as
HashSet<Integer> hset = new HashSet<Integer>();
but here the problem is,how could i declare the type of objects stored in HashSet i,e Integer, bacause in the above declaration the HashSet is rawtype.
I would like to add more here,
You need to initialize your outer Map like below
HashMap<Integer,HashSet<Integer>> map = new HashMap<Integer,HashSet<Integer>>();
and inner collection like this
HashSet<Integer> hset = new HashSet<Integer>();
And you insert the values like below in map and your hash set.
hset.add(1);
hset.add(2);
map.put(100,hset);
hset = new HashSet<Integer>();
hset.add(3);
hset.add(4);
map.put(101,hset);
So every time you need new instance of HashSet to put in map.
You can get inner HashSet by using Map key you used to insert.
HashSet<Integer> hset=map.get(100); //Same map
Here is your declaration should look like
HashMap<Integer,HashSet<Integer>> map = new HashMap<Integer>,HashSet<Integer>>
Second declaration you have provided for Hashset is correct. Its not raw type. Did you try adding a any other type of element to it ?
Try this it will work :
Map<Integer, Set<Integer>> map = new HashMap<Integer, Set<Integer>>();
you can easily Set Using Map tag only .
or
Create the Object Of Hashmap and put the value from Refrence. it will work
static Map<Integer,HashMap<String,HashMap<String,String>>> maps = new HashMap<Integer, HashMap<String,HashMap<String,String>>>();
I want to insert the elements inside the HashMap I declared above , the inner most hashmap has values ready which I can use , now I am using it like ,
static Map<String,String> values = new HashMap<String, String>();
maps.put(1, new HashMap<<new String("")>, values>());
How can I achieve this ?
static Map<String,String> values1 = new HashMap<String,String>();
static Map<String,Map<String,String>> values2 = new HashMap<String,Map<String,String>>();
values2.put("", values1);
maps.put(1,values2);
btw, if you have java 7, you can use:
Map<String,String> values1 = new HashMap<>();
and so on for others
In cases you have map inside a map (inside a map), consider using Apache MultiKeyMap.
Coding will be more intuitive
It will improve the readability of your code
It will prevent many if(map.get(key) != null) blocks you will probably have in your code.
Why not to have instance of HashMap. When you wan to insert new value, you need to have Integer, String, String key and String value.
You continuously select nested HashMaps according to keys and then insert value to the most inner HashMap.
map.get(key1).get(key2).insert(key3, value)