How do I put values in this map?
public static Map<String, TreeMap<String, SomeClass>> myMap=Collections.synchronizedMap(new TreeMap<String, TreeMap<String,SomeClass>>());
First you need to make sure the "inner map" exists, then you can put values into it:
String outerKey = "exampleKey1";
String innerKey = "exampleKey2";
SomeClass innerValue = new SomeClass();
TreeMap<String, SomeClass> innerMap = myMap.get(outerKey);
if (innerMap == null) {
innerMap = Collections.synchronizedMap(new TreeMap<String, SomeClass>());
myMap.put(outerKey, innerMap);
}
innerMap.put(innerKey, innerValue);
You should also consider changing the type to:
public static Map<String, SortedMap<String, SomeClass>> myMap = ...
// ^^^^^^^^^
or just Map depending on if you need the sorted property.
TreeMap<String, SomeClass> map = myMap.get(key1)
if(map == null) {
map = Collections.synchronizedMap(new TreeMap<String, SomeClass>());
myMap.put(key1, map);
}
map.put(key2, value);
TreeMap<String, SomeClass> value = new TreeMap<String, SomeClass>();
myMap.put("key", value);
Related
My parentMap is look like something below.
HashMap<String, Integer>>> parentMap = {disabled={account={test1=22}, group={test2=10}}}
What I suppose to do is, if operationType=disabled and objectType=account or group etc and testName=test1 or test2 etc then I suppose to increase the count of test1 by 1.
I have to update the same map so that at the end I should get some statistic like there are 22 tests cases of objectType=account and 10 tests cases of objectType=group etc are disabled
I tried something below but it is going in infinite loop as I'm putting values in the map and iterating over it again.
private HashMap<String, HashMap<String, HashMap<String, Integer>>> countTags(String statType, String objectType,
String opType, HashMap<String, HashMap<String, HashMap<String, Integer>>> parentMap) {
if (!Util.isEmpty(parentMap)) {
//created new map to avoid infinite loop here but no luck :(
HashMap<String, HashMap<String, Integer>> objMap = new HashMap<>();
objMap.putAll(parentMap.get(statType));
Iterator<Entry<String, HashMap<String, Integer>>> it = objMap.entrySet().iterator();
while (it.hasNext()) {
Entry<String, HashMap<String, Integer>> operationEntry = it.next();
HashMap<String, Integer> operationMap = operationEntry.getValue();
Set<String> opKeySet = operationMap.keySet();
Iterator<String> opIt = opKeySet.iterator();
while (opIt.hasNext()) {
parentMap.put(statType, countTags(objectType, opType, operationMap));
}
}
} else {
parentMap.put(statType, countTags(objectType, opType, new HashMap<String, Integer>()));
}
return parentMap;
}
private HashMap<String, HashMap<String, Integer>> countTags(String objectType, String opType, HashMap<String, Integer> tagMap) {
int testRepeatCount = tagMap.get(opType) != null ? tagMap.get(opType) : 0;
tagMap.put(opType, 1 + testRepeatCount);
HashMap<String, HashMap<String, Integer>> objMap = new HashMap<>();
objMap.put(objectType, tagMap);
return objMap;
}
I found
a.compute(key, (k, v) -> v == null ? 1 : v + 1); also some suggestions here Java map.get(key) - automatically do put(key) and return if key doesn't exist? but can I get some help how optimally I should achieve my desired outcome here?
I finally get out of my own if_else mess. this is how my final method is look a like. This helped me here Java append `HashMap` values to existing HashMap if key matches
private HashMap<String, HashMap<String, HashMap<String, Integer>>> countTags(String statType, String objectType,
String opType, HashMap<String, HashMap<String, HashMap<String, Integer>>> parentMap) {
if (!Util.isEmpty(parentMap) && parentMap.containsKey(statType)) {
// if objType is present, count the tags
if (parentMap.get(statType).containsKey(objectType)) {
HashMap<String, Integer> objMap = parentMap.get(statType).get(objectType);
HashMap<String, Integer> map = countTags(objectType, opType, objMap).get(objectType);
parentMap.get(statType).get(objectType).putAll(map);
} else {
// if objType isn't present, add that objType and count the tags
HashMap<String, HashMap<String, Integer>> map = countTags(objectType, opType,
new HashMap<String, Integer>());
parentMap.get(statType).put(objectType, map.get(objectType));
}
} else {
// first time add the new tag to calculate it's object/operation wise
// distribution
parentMap.put(statType, countTags(objectType, opType, new HashMap<String, Integer>()));
}
return parentMap;
}
Given the following situation:
Map<String, Object> map1 = new HashMap();
Map<String, String> map2 = new HashMap();
map2.put("Grp A", "a");
map2.put("Grp B", "b");
map1.put("Grp",map2);
How can get the "Grp A" value from map1 ?
Change map1 to:
Map<String, Map<String, String>> map1 = new HashMap<>();
Then map1.get("Grp").get("Grp A") will work.
Of course, in general it would be safer to store map1.get("Grp") in a variable, and check if it's not null before calling the second get():
String value = null;
Map<String, String> inner = map1.get("Grp");
if (inner != null) {
value = inner.get("Grp A");
}
If you must keep map1 as Map<String, Object> (for example, if you must store values of different types in it), you'll have to check the type of the value you got from the outer Map, and cast it to a Map before obtaining the inner value:
String value = null;
Object innerObj = map1.get("Grp");
if (innerObj instanceof Map<?,?>) {
Map<?,?> inner = (Map<?,?>) map1.get("Grp");
Object obj = inner.get("Grp A");
if (obj instanceof String) {
value = (String) obj;
}
}
Simply retrieve map2 from map1 by casting to a Map and then get the desired value from that Map:
return ((Map<String,String>)map1.get("Grp")).get("Grp A");
However, better practice would be to check that map2 isn't null before retrieving "Grp A":
Map<String,String> map = (Map<String,String>)map1.get("Grp");
if (map != null) {
return map.get("Grp A");
}
#Eran's answer would be better practice, but OP asked how to retrieve the value from the given HashMap.
Since you defined map1 as Map<String, Object> it's values are returned as objects.
You can solve this by either by .
Casting .
Map<String,String> map2 = = (Map<String,String>)map1.get("Gep")
Using the right generics for m1 .
Map<String, Map<String, String>> map1 = new HashMap<>();
Below is the solution for the above problem
import java.util.HashMap;
import java.util.Map;
public class HashMapExample {
public static void main(String[] args) {
Map<String, String> map2 = new HashMap<>();
Map<String, Map<String, String>> map1 = new HashMap<>();
map2.put("Grp A", "a");
map2.put("Grp B", "b");
map1.put("Grp",map2);
System.out.println(map1.get("Grp").get("Grp A"));
}
}
Hope this will work
Thanks...
It's a simple question,
I have a simple HashMap of which i want to reverse the keys and values.
HashMap<Character, String> myHashMap = new HashMap<Character, String>();
myHashMap.put('a', "test one");
myHashMap.put('b', "test two");
and I want to create a new HashMap in which i put the opposites.
HashMap<String, Character> reversedHashMap = new HashMap<String, Character>();
e.g. Keys "test one" & "test two" and values 'a' & 'b'.
They all are unique, yes
If you're sure that your values are unique you can iterate over the entries of your old map .
Map<String, Character> myNewHashMap = new HashMap<>();
for(Map.Entry<Character, String> entry : myHashMap.entrySet()){
myNewHashMap.put(entry.getValue(), entry.getKey());
}
Alternatively, you can use a Bi-Directional map like Guava provides and use the inverse() method :
BiMap<Character, String> myBiMap = HashBiMap.create();
myBiMap.put('a', "test one");
myBiMap.put('b', "test two");
BiMap<String, Character> myBiMapInversed = myBiMap.inverse();
As java-8 is out, you can also do it this way :
Map<String, Integer> map = new HashMap<>();
map.put("a",1);
map.put("b",2);
Map<Integer, String> mapInversed =
map.entrySet()
.stream()
.collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey))
Finally, I added my contribution to the proton pack library, which contains utility methods for the Stream API. With that you could do it like this:
Map<Character, String> mapInversed = MapStream.of(map).inverseMapping().collect();
Apache commons collections library provides a utility method for inversing the map. You can use this if you are sure that the values of myHashMap are unique
org.apache.commons.collections.MapUtils.invertMap(java.util.Map map)
Sample code
HashMap<String, Character> reversedHashMap = MapUtils.invertMap(myHashMap)
If the values are not unique, the safe way to inverse the map is by using java 8's groupingBy function
Map<String, Integer> map = new HashMap<>();
map.put("a",1);
map.put("b",2);
Map<Integer, List<String>> mapInversed =
map.entrySet()
.stream()
.collect(Collectors.groupingBy(Map.Entry::getValue, Collectors.mapping(Map.Entry::getKey, Collectors.toList())))
I wrote a simpler loop that works too (note that all my values are unique):
HashMap<Character, String> myHashMap = new HashMap<Character, String>();
HashMap<String, Character> reversedHashMap = new HashMap<String, Character>();
for (char i : myHashMap.keySet()) {
reversedHashMap.put(myHashMap.get(i), i);
}
To answer your question on how you can do it, you could get the entrySet from your map and then just put into the new map by using getValue as key and getKey as value.
But remember that keys in a Map are unique, which means if you have one value with two different key in your original map, only the second key (in iteration order) will be kep as value in the new map.
Iterate through the list of keys and values, then add them.
HashMap<String, Character> reversedHashMap = new HashMap<String, Character>();
for (String key : myHashMap.keySet()){
reversedHashMap.put(myHashMap.get(key), key);
}
private <A, B> Map<B, A> invertMap(Map<A, B> map) {
Map<B, A> reverseMap = new HashMap<>();
for (Map.Entry<A, B> entry : map.entrySet()) {
reverseMap.put(entry.getValue(), entry.getKey());
}
return reverseMap;
}
It's important to remember that put replaces the value when called with the same key. So if you map has two keys with the same value only one of them will exist in the inverted map.
Tested with below sample snippet, tried with MapUtils, and Java8 Stream feature. It worked with both cases.
public static void main(String[] args) {
Map<String, String> test = new HashMap<String, String>();
test.put("a", "1");
test.put("d", "1");
test.put("b", "2");
test.put("c", "3");
test.put("d", "4");
test.put("d", "41");
System.out.println(test);
Map<String, String> test1 = MapUtils.invertMap(test);
System.out.println(test1);
Map<String, String> mapInversed =
test.entrySet()
.stream()
.collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey));
System.out.println(mapInversed);
}
Output:
{a=1, b=2, c=3, d=41}
{1=a, 2=b, 3=c, 41=d}
{1=a, 2=b, 3=c, 41=d}
Use forEach introduced in Java 8
Map<Short, String> regularMap = new HashMap<>();
Map<String, Short> inversedMap = new HashMap<>();
regularMap.forEach((key, value) -> inversedMap.put(value, key));
for reverting the map, in your case:
private void reverseMap(Map<Character, String> map) {
Map<String, Character> newList = new HashMap<>();
map.forEach((key, value) -> newList.put(value, key));
System.out.println(newList);
}
or you can traverse the old hashmap
HashMap<String, Character> newList = new HashMap<String, Character>();
for (String key : list.keySet()){
newList.put(list.get(key), key);
}
For Reversing the Array of Dictionary. (If values are Unique)
private void reverseArrayMap(List<Map<String, String>> list) {
// reversing the array of dictionary
List<Map<String, String>> newList = new ArrayList<>();
Map<String, String> resDic = new HashMap<>();
for (Map<String, String> map : list) {
map.forEach((key, value) -> resDic.put(value, key));
newList.add(resDic);
}
System.out.println("Original Array of Dictionary" + list);
System.out.println("Reversed Array of Dictionary" + newList);
}
Java :
Simple approach, No need for java 8
Map<String,String> map=new HashMap<>();
Map<String,String> mapInv=new HashMap<>();
for (String key : map.keySet())
mapInv.put(map.get(key), key);
Java 8:
forEach() is a new method to iterate the elements. It is defined in Iterable and Stream interface.
Map<String,String> map=new HashMap<>();
Map<String,String> mapInv=new HashMap<>();
map.forEach((key, value) -> mapInv.put(value, key));
Kotlin :
val map: Map<String, String> = HashMap()
val mapInv: MutableMap<String?, String> = HashMap()
for (key in map.keys) mapInv[map[key]] = key
Please, help me convert a HashMap<String, ArrayList<String>> to HashMap <String, String>, where each ArrayList should be converted into one String that contains the ArrayList's elments.
I believe that this is what you are looking for.
//HashMap<String, ArrayList<String>> hashMap;
//initialized somewhere above
HashMap<String, String> newHashMap = new HashMap<>();
for (Map.Entry<String, ArrayList<String>> entry : hashMap.entrySet())
{
newHashMap.put(entry.getKey(), entry.getValue().toString());
}
Not sure if your issue was with toString() or how to iterate over a HashMap, if it was the latter, here's how to iterate over a map.
Here's a from-start-to-finish example:
ArrayList<String> al = new ArrayList<>();
al.add("The");
al.add("End");
HashMap<String, ArrayList<String>> hashMap = new HashMap<>();
hashMap.put("This is", al);
HashMap<String, String> newHashMap = new HashMap<>();
for (Map.Entry<String, ArrayList<String>> entry : hashMap.entrySet())
{
newHashMap.put(entry.getKey(), entry.getValue().toString());
}
System.out.println(newHashMap.toString());
//prints {This is=[The, End]}
I have a method in a class, which initialize a HashMap and put some keys and values inside it, then the method returns the HashMap. How can I retrieve the returned HashMap?
public Map<String, String> getSensorValue(String sensorName) {
registerSensor(sensorName);
sensorValues.put("x","25");
sensorValues.put("y","26");
sensorValues.put("z","27");
return sensorValues;
}
And here I call this method from another class:
public static HashMap<String, String> sensValues = new HashMap<String, String>();
AllSensors sensVal = new AllSensors();
sensValues.putAll(sensVal.getSensorValue("orientation"));
String something = sensValues.get("x");
But it does not work in this way
sensValues.putAll(sensVal.getSensorValue("orientation"));
Makes my android application crash.
The point is to retrive returned HashMap somehow.
You shouldn't have to copy the map. Just try using the returned reference:
Map<String, String> map = sensVal.getSensorValue("...");
Your method needs to return a Map<String,String>. In the code you have posted, the Map sensorValues is never initialized.
public Map<String, String> getSensorValue(String sensorName) {
Map<String,String> sensorValues = new HashMap<String,String>();
registerSensor(sensorName);
sensorValues.put("x","25");
sensorValues.put("y","26");
sensorValues.put("z","27");
return sensorValues;
}
Almost as Rich said in his answer, but your method returns a Map which cannot be cast to a HashMap. Try this
Map<String, String> map = sensVal.getSensorValue("...");
Or alternatively change your getSensorValue method so that it returns a HashMap
HashMap sensValues = new HashMap();
Set mapSet = (Set) sensValues.entrySet();
Iterator mapIterator = mapSet.iterator();
while (mapIterator.hasNext()) {
Map.Entry mapEntry = (Map.Entry) mapIterator.next();
String keyValue = (String) mapEntry.getKey();
String value = (String) mapEntry.getValue();
System.out.println("Key : " + keyValue + "= Value : " + value);
}
Also you can try pass by reference aproach,
void main(){
public static HashMap<String, String> sensValues = new HashMap<String, String>();
AllSensors sensVal = new AllSensors();
sensVal.setSensorValue(sensValues ,"orientation");
String something = sensValues.get("x");
}
public void setSensorValue(Map<String, String> sensorValues, String sensorName) {
registerSensor(sensorName);
sensorValues.put("x","25");
sensorValues.put("y","26");
sensorValues.put("z","27");
}