Im storing 2 map with different structure in single map like below,
Map<String, List<String>> colMap = new HashMap<String, List<String>>();
Map<String, String> appMap = new HashMap<String, String>();
// colMap assigning some values
// appMap assigning some values
Map<String, Map> mainMap = new HashMap<String, Map>();
mainMap.put("appMap", appMap);
mainMap.put("colMap", colMap);
I want to get map one by one and iterate the map.
If I try get map like below, getting error,
.......
Map colMap = map.get("colMap");
for(Entry<String, List<String>> entry : colMap.entrySet())
Error: Type mismatch: cannot convert from element type Object to Map.Entry<String,List<String>>
Why not just create a simple container POJO class (or record in Java 16+) for the two maps instead of mainMap and keep the relevant type-safety which to do it Java-way?
public class MapPojo {
private final Map<String, List<String>> colMap;
private final Map<String, String> appMap;
public MapPojo(Map<String, List<String>> colMap, Map<String, String> appMap) {
this.colMap = colMap;
this.appMap = appMap;
}
// getters, etc.
}
MapPojo mainMap = new MapPojo(colMap, appMap);
Error you are getting because when you are doing map.get operation your reference is Just Map without any Generics which will treated as Object class's reference. You should use generics like below and it will work -
Map<String, List<String>> colMap = map.get("colMap");
for(Entry<String, List<String>> entry : colMap.entrySet())
Related
I have a nested maps object like below
{12345={{"status":"200","outcome":"Success","message":"Account created"}}
{23121={{"status":"400","outcome":"Exception","message":"Invalid State value"}}
{43563={{"status":"200","outcome":"Success","message":"Account updated"}}
{72493={{"status":"400","outcome":"Exception","message":"Bad Request"}}
I need to transform this into Map<String, List<Map<String, Map<String, String>>> where the key of outer map is value of the status ( 200 or 400 ) and the value is the list of original maps that have status = 200 or 400 or other valid values from the inner map.
So, the new structure would look like
{{200={[{12345={"status":"200","outcome":"Success","message":"Account created"}},
{43563={"status":"200","outcome":"Success","message":"Account updated"}}
]
},
{400={[{23121={"status":"400","outcome":"Exception","message":"Invalid State value"}},
{72493={"status":"400","outcome":"Exception","message":"Bad Request"}}
]
}
}
Ultimately, I need to generate a report based on the different stati.
This is what I have started with, but am stuck.
I want to loop through outer map, get the inner map, get the value of status key and add the map to a list based on status code value.
This is how I am doing it using loops
private static Map<String, List<Map<String, Map<String, String>>>> covertToReport(Map<String, Map<String, String>> originalMap) {
Map<String, List<Map<String, Map<String, String>>>> statusBasedListOfMaps = new TreeMap<>();
//loop through the map
//for each key, get the inner map
//get the status value for each inner map
List<Map<String, Map<String, String>>> accountsMapsList;
for (Entry<String, Map<String, String>> entry : originalMap.entrySet()) {
String accNum = entry.getKey();
Map<String, String> childMap = entry.getValue();
String stausVal = childMap.get("status");
accountsMapsList = statusBasedListOfMaps.get(stausVal) == null ? new ArrayList<>() : statusBasedListOfMaps.get(stausVal);
accountsMapsList.add((Map<String, Map<String, String>>) entry);
statusBasedListOfMaps.put(stausVal, accountsMapsList);
}
return statusBasedListOfMaps;
}
Of course, the below code doesn't compile, but that is what I am trying to get.
private static void covertToReport(Map<String, Map<String, String>> originalMap) {
Map<String, List<Map<String, Map<String, String>>>> statusBasedListOfMaps;
statusBasedListOfMaps = originalMap.entrySet()
.stream()
.filter(e -> e.getValue()
.values()
.stream()
.map(innerMap -> Collectors.toList())
.collect(Collectors.toMap(Map.Entry::getKey, Collectors.toList(e)));
Is this possible?
You can just use Collectors.groupingBy() with Collectors.mapping():
private static Map<String, List<Map<String, Map<String, String>>>> convertToReport(Map<String, Map<String, String>> originalMap) {
return originalMap.entrySet().stream()
.collect(Collectors.groupingBy(e -> e.getValue().get("status"),
Collectors.mapping(Map::ofEntries, Collectors.toList())));
}
You group by status and then map the associated entry to an own map using Map.ofEntries(). If you are using Java you can use this instead of Map::ofEntries:
e -> new HashMap<>() {{ put(e.getKey(), e.getValue()); }}
The result will be this:
200=[
{12345={status=200, message=Account created, outcome=Success}},
{43563={status=200, message=Account created, outcome=Success}}
],
400=[
{72493={status=400, message=Invalid State value, outcome=Exception}},
{23121={status=400, message=Invalid State value, outcome=Exception}}
]
Your function return a Map<String, List<Map<String, Map<String, String>>>>, but your structure look like Map<String, Map<String, Map<String, String>>>
If what you really like is a Map<String, Map<String, Map<String, String>>> here is the code:
Map<String, Map<String, Map<String, String>>> result= map.entrySet().stream().collect(Collectors.groupingBy(entry -> entry.getValue().get("status"), Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)));
I have an outerMap which contains an innerMap for each key it got. At first, every innerMap is the same (here, they contain {1=1}.
I want to change the value of one certain innermap, for a certain key.
Here is my code:
public class HelloWorld
{
public static void main(String args[]){
HashMap<String, HashMap<String, Integer>> outerMap = new HashMap<String, HashMap<String, Integer>>();
HashMap<String, Integer> innerMap = new HashMap<String, Integer>();
outerMap.put("1001",innerMap);
outerMap.put("1002",innerMap);
outerMap.put("1003",innerMap);
innerMap.put("1", 1);
//My attempt to change only one innermap;
Map<String, Integer> map_to_change = outerMap.get("1001");
map_to_change.put("1", 0);
//And then I print them to see if it's working;
for(Map.Entry map : outerMap.entrySet() )
{
System.out.println(map.getKey()+" "+map.getValue());
}
}
}
However, the output here is
1003 {1=0}
1002 {1=0}
1001 {1=0}
Which shows that my code changes all innermaps, and not only the one linked with the key "1001".
What can I do?
You are pointing the same innerMap object in the outerMap,
outerMap.put("1001",new HashMap<String, Integer>());//create separate maps
outerMap.put("1002",new HashMap<String, Integer>());
outerMap.put("1003",new HashMap<String, Integer>());
HashMap<String, Integer> innerMap =outerMap.get("1001");//get the map you want to put value
innerMap.put("1", 1);//assign the value
Update:
If you want to retain a copy of Map which you have already created, you can copy and create a new Map from it using putAll method,
outerMap.put("1001",copyMap(innerMap));
outerMap.put("1002",copyMap(innerMap));
outerMap.put("1003",copyMap(innerMap));
copyMap method looks like,
private static HashMap<String, Integer> copyMap(HashMap<String, Integer> innerMap){
HashMap<String, Integer> copiedInnerMap = new HashMap<String, Integer>();
copiedInnerMap.putAll(innerMap);
return copiedInnerMap;
}
I want to add an Arraylist<String> object(inputArrListObj) into my already existing Map<String, String> (param) which has some input values to be sent.
Map<String,String> param = new HashMap<String, String>();
List<String> obj = inputArrListObj;
param.put("1","Value");
//param.put("2",<Input list values>);
What should be the ideal approach to do the same?
It is not possible with your current declaration.
You must consider changing your map declaration to
Map<String,List<String>> param = new HashMap<String, List<String>>();
That allows you to insert a List as value.
However for the first case (param.put("1","Value");), your List will have only one String in it.
It's look like you want to store in your map abstract named values. If so try to use Map<String, Object> and cast to specific class when you get values from map.
Map<String, Object> param = new HashMap<String, Object>();
List<String> obj = inputArrListObj;
param.put("1", "Value");
param.put("2", obj);
...
List<String> param2 = (List<String>) param.get("2");
I have map of maps
Map<String, Map<String,Integer>> outerMap = new HashMap<String, Map<String, Integer>>();
and I want to put some values to inner map. Is that correct way? Or it can be done better?
class SampleMap {
Map<String, Map<String, Integer>> outerMap = new HashMap<String, Map<String, Integer>>();
public void add(String outerKey, String innerKey, Integer value) {
Map<String, Integer> tempMap = new HashMap<String, Integer>();
if (outerMap.size() > 0)
tempMap = outerMap.get(outerKey);
tempMap.put(innerKey, value);
outerMap.put(key, tempMap);
}
}
You can improve the code by avoiding the creation of a new inner map eagerly, until the point when you know that you must create it.
In addition, if you know that the inner map instance came from the outer map, you don't have to spend time putting it back where it came from.
public void add(String outerKey, String innerKey, Integer value) {
Map<String, Integer> tempMap
if (outerMap.containsKey(outerKey)) {
tempMap = outerMap.get(outerKey);
} else {
tempMap = new HashMap<String, Integer>();
outerMap.put(outerKey, tempMap);
}
tempMap.put(innerKey, value);
}
Technically there is nothing wrong in your code (except a minor improvement suggested by dasblinkenlight), but is map of maps what you really need?
If you want to read/write values by two keys, probably it's better to create map from pair of two keys (MultiKey or Pair implementation can be used) or another data structure (see this comment for details https://stackoverflow.com/a/3093993/554281)
I'm new to Java, but not new to programming, so as my first project I decided to create a .txt-.csv parser for someone at work. I read each line in the .txt file and separate it into separate Maps for sections, subsections, subsubsections, and the subsubsections' contents. Each Map is then assigned to the Map above it (more on this below). I print everything to it just fine, but when I try to read it I get the following error: "java.lang.String cannot be cast to java.util.Map". The error only appears after the code is run, not while compiling, nor in NetBeans IDE.
My Maps are in the following form with each Object being the Map below it: (Why can't Java make this easy -_- Associative Arrays are all I want)
(Map)array=<string,Object>
(Map)subarray=<String,Object>
(Map)subsubarray=<String,Object>
(Map)subsubcontents=<String,String>
May not be the most efficient way to read this, plan on converting this to recursive function later, but here is my code, copy-pasted from my project. I put comments at where I've found the error to be.
public static Map<String,Object> array=new HashMap<String,Object>();
/* Code for populating the following Maps and pushing them into array
<String,Object>subarray
<String,Object>subsubarray
<String,String>subsubcontents
*/
Set section=array.entrySet();
Iterator sectionI=section.iterator();
while(sectionI.hasNext()) {
Map.Entry sectionInfo=(Map.Entry)sectionI.next();
Map<String,Object> subMap=(Map)sectionInfo.getValue();
Set subSet=subMap.entrySet();
Iterator subI=subSet.iterator();
while(subI.hasNext()) {
Map.Entry subInfo=(Map.Entry)subI.next();
Map<String,Object> subsubMap=(Map)subInfo.getValue();
Set subsubSet=subsubMap.entrySet();
Iterator subsubI=subsubSet.iterator();
while(subsubI.hasNext()) {
System.out.println("test");
Map.Entry subsubInfo=(Map.Entry)subsubI.next();
Map<String,Object> subcontentsMap=(Map)subsubInfo.getValue();
/*
The above line seems to be causing the issues.
If you comment out the rest of this loop (below this comment)
the error will still appear. If you comment out the rest of this loop
(including the line above this comment) it disappears.
Power of deduction my dear Watson.
*/
Set subcontentsSet=subcontentsMap.entrySet();
Iterator keys=subcontentsSet.iterator();
while(keys.hasNext()) {
Map.Entry keyMap=(Map.Entry)keys.next();
}
Iterator values=subcontentsSet.iterator();
while(values.hasNext()) {
Map.Entry valueMap=(Map.Entry)values.next();
}
}
}
}
Any help would be much appreciated. I've been struggling with this for a couple of days now.
I think you need to clean up your generics to start with:
Set<Map.Entry<String, Object>> section = array.entrySet();
Iterator<Map.Entry<String, Object>> sectionI = section.iterator();
while (sectionI.hasNext()) {
Map.Entry<String, Object> sectionInfo = sectionI.next();
Map<String, Object> subMap = (Map<String, Object>) sectionInfo.getValue(); // is this actually a Map<String, Object>?
Set<Map.Entry<String, Object>> subSet = subMap.entrySet();
Iterator<Map.Entry<String, Object>> subI = subSet.iterator();
while (subI.hasNext()) {
Map.Entry<String, Object> subInfo = subI.next();
Map<String, Object> subsubMap = (Map<String, Object>) subInfo.getValue(); // is this actually a Map<String, Object>?
Set<Map.Entry<String, Object>> subsubSet = subsubMap.entrySet();
Iterator<Map.Entry<String, Object>> subsubI = subsubSet.iterator();
while (subsubI.hasNext()) {
System.out.println("test");
Map.Entry<String, Object> subsubInfo = subsubI.next();
Map<String, Object> subcontentsMap = (Map<String, Object>) subsubInfo.getValue(); // somehow a String got in here?
/*
The above line seems to be causing the issues.
If you comment out the rest of this loop (below this comment)
the error will still appear. If you comment out the rest of this loop
(including the line above this comment) it disappears.
Power of deduction my dear Watson.
*/
Set<Map.Entry<String, Object>> subcontentsSet = subcontentsMap.entrySet();
Iterator<Map.Entry<String, Object>> keys = subcontentsSet.iterator();
while (keys.hasNext()) {
Map.Entry<String, Object> keyMap = keys.next();
}
Iterator<Map.Entry<String, Object>> values = subcontentsSet.iterator();
while (values.hasNext()) {
Map.Entry<String, Object> valueMap = values.next();
}
}
}
}
Then, you should be more explicit with your declaration of array:
public static Map<String, Map<String, Map<String, Map<String, String>>>> array = new HashMap<String, Map<String, Map<String, Map<String, String>>>>();
This would ensure that you are putting the correct objects into each of the maps. You will never be able to put a String value where a Map<> is expected because it will not compile. This will allow you to write the following code (without needing casts):
final Set<Map.Entry<String, Map<String, Map<String, Map<String, String>>>>> section = array.entrySet();
final Iterator<Map.Entry<String, Map<String, Map<String, Map<String, String>>>>> sectionI = section.iterator();
while (sectionI.hasNext()) {
final Entry<String, Map<String, Map<String, Map<String, String>>>> sectionInfo = sectionI.next();
final Map<String, Map<String, Map<String, String>>> subMap = sectionInfo.getValue();
final Set<Map.Entry<String, Map<String, Map<String, String>>>> subSet = subMap.entrySet();
final Iterator<Map.Entry<String, Map<String, Map<String, String>>>> subI = subSet.iterator();
while (subI.hasNext()) {
final Map.Entry<String, Map<String, Map<String, String>>> subInfo = subI.next();
final Map<String, Map<String, String>> subsubMap = subInfo.getValue();
final Set<Map.Entry<String, Map<String, String>>> subsubSet = subsubMap.entrySet();
final Iterator<Map.Entry<String, Map<String, String>>> subsubI = subsubSet.iterator();
while (subsubI.hasNext()) {
System.out.println("test");
final Map.Entry<String, Map<String, String>> subsubInfo = subsubI.next();
final Map<String, String> subcontentsMap = subsubInfo.getValue();
final Set<Map.Entry<String, String>> subcontentsSet = subcontentsMap.entrySet();
final Iterator<Map.Entry<String, String>> entries = subcontentsSet.iterator();
while (entries.hasNext()) {
final Map.Entry<String, String> entry = entries.next();
}
}
}
}
All that being said, all of those nested generics look ugly. I'd recommend you create some objects to represent your data.
You can do this :
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonElement element = gson.fromJson (jsonString, JsonElement.class);
JsonObject jsonObj = element.getAsJsonObject();
Map<String,Object> resultMap = new Gson().fromJson(jsonObj, Map.class);
The exception tells you everything. This call subsubInfo.getValue(); is actually returning a String, not a Map, so you have a logical error when creating your maps.
The compiler will warn you about this if you change your declarations to Map<String, Map> instead of Map<String, Object>