I am new in java generics and facing following issues.
I have have method like,
private static void fillDescriptiveData(HashMap<String, Object> output, String attributeMapping) {
for (Map.Entry<String, Object> outputInEntry : output.entrySet()) {
String outputKey = outputInEntry.getKey();
String outputValue = outputInEntry.getValue().toString();
outputValue = getDescriptiveDataForOutput(outputKey, outputValue, attributeMapping);
outputInEntry.setValue(outputValue);
}
}
Now if I call API as below way
HashMap<String, Object> ObjectMap = new HashMap<String, Object>();
HashMap<String, List> listMap = new HashMap<String, List>();
fillDescriptiveData(ObjectMap,"here");
this one working fine.
fillDescriptiveData(listMap,"here");
this call gives error
The method fillDescriptiveData(HashMap, String) in the type CustomAttribute is not applicable for the arguments (HashMap, String)`
why ?
In row to solve this issue I encounter with one more issue,
private static void fillDescriptiveData(HashMap<String, ? extends Object> output, String attributeMapping) {
for (Map.Entry<String, ? extends Object> outputInEntry : output.entrySet()) {
String outputKey = outputInEntry.getKey();
String outputValue = outputInEntry.getValue().toString();
outputValue = getDescriptiveDataForOutput(outputKey, outputValue, attributeMapping);
outputInEntry.setValue(outputValue); /* Error comes at this line */
}
}
HashMap<String, ? extends Object> ObjectMap = new HashMap<String, Object>();
HashMap<String, List> listMap = new HashMap<String, List>();
fillDescriptiveData(ObjectMap,"here");
fillDescriptiveData(listMap,"here");
error at line - outputInEntry.setValue(outputValue);
The method setValue(capture#4-of ? extends Object) in the type
Map.Entry is not applicable for
the arguments (String)
why ?
What is the best way to avoid this issues ?
This is the case when you could use type variables:
private static <T> void fillDescriptiveData(Map<String, T> output,String attributeMapping)
{
for(Map.Entry<String, T> outputInEntry : output.entrySet())
{
String outputKey = outputInEntry.getKey();
String outputValue = outputInEntry.getValue().toString();
outputValue = getDescriptiveDataForOutput(outputKey, outputValue, attributeMapping);
outputInEntry.setValue((T) outputValue);
}
}
More specifically, your second type-parameter in the map is unbounded. Object will not work here as it is specific class. ? extends Object is somewhat nonsense.
Just HashMap<String, ?> would work until you will just read the map, but you will not be able to put something here. So only one way - using type variable.
EDIT: One more thing: please, use interfaces where it's possible. So here instead of HashMap<String, T> better use Map<String, T>. It isn't a mistake, just good and proper style of code.
The error with this line:
outputInEntry.setValue(outputValue);
Is that you're always putting a string into the entry. This will only work if the entry is of type ? super String, or exactly String. So it will not work for a Map<String, Object> or Map<String, List>.
It seems like you just want to map each value to a string. You can do it, but to be type safe, you need to create a new Map<String, String>. Since you're always mapping to a String.
If you for instance pass in a Map<String, List<?>> and (unsafely) replace all the values with strings. Someone could still keep using the Map<String, List<?>> that was passed into the function, but it now contains strings as values instead of lists. When they try to retrieve a List from it they get a class cast exception.
Something like this:
private static Map<String, String> fillDescriptiveData(HashMap<String, ?> input,
String attributeMapping) {
Map<String, String> output = new HashMap<>();
for(Entry<String, ?> e : input.entrySet()) {
String outputKey = e.getKey();
String outputValue = e.getValue().toString();
outputValue
= getDescriptiveDataForOutput(outputKey, outputValue, attributeMapping);
output.put(outputKey, outputValue);
}
return output;
}
Map<String, String> r1 = fillDescriptiveData(ObjectMap, "here");
Map<String, String> r2 = fillDescriptiveData(listMap, "here");
Related
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())
i want this type of hashtable or vector or etc.,
Hashtable<Integer, String, String > hashtbl=new Hashtable<Integer, String, String>();
You can create a object which accept two parameters like below :
public class MyObject {
public MyObject(String val1, String val2) {
...
}
}
Then you can use this object as the value of a Map :
Map<Integer, MyObject> myMap = new HashMap<>();
myMap.put(1,new MyObject("value_1", "value_2"));
You can use a HashMap of HashMaps like this:
HashMap<Integer, HashMap<String, String>> mashmap= new HashMap<Integer, HashMap<String, String>>();
When you want to add a value to Hashmap, you need to instantiate it too:
HashMap<String, String> val = new HashMap<String, String>();
// Do what you want to do with val
mashmap.put(Key, val);
This is not possible if we write this type of scenario we get the exception like:
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Incorrect number of arguments for type Hashtable; it cannot be parameterized with arguments
Incorrect number of arguments for type Hashtable; it cannot be parameterized with arguments
An API I am using has a method that returns a Map<String, Object>, but I know the Object's are String's in this case, so I want it as a Map<String, String>.
But for some reason I can't just cast it, Java says Map<String, Object> cannot be casted to Map<String, String>, for some reason.
I used:
Map<String, Object> tempMap = someApiMethodReturningAMap();
Map<String, String> map = new HashMap<String, String>();
for (String i : tempMap.keySet()) {
map.put(i, String.valueOf(tempMap.get(i)));
}
as a workaround, but is there an easier way?
Well you can't safely cast it to a Map<String, String> because even though you know you've only got strings as the values, the compiler doesn't. That's like expecting:
Object x = "foo";
String y = x;
to work - it doesn't; you need to explicitly cast.
Likewise you can explicitly cast here, too, if you go via Object:
Map<String, Object> x = ...;
Map<String, String> y = (Map<String, String>) (Object) x;
Now you'll get a warning saying that it's an unchecked cast, because unlike the earlier "object to string" cast, there's no execution-time check that it's really valid. Type erasure means that a map doesn't really know its key/value types. So you end up with checking only being done when elements are fetched:
import java.util.*;
class Test {
public static void main(String[] args) {
Map<String, Object> x = new HashMap<>();
x.put("foo", "bar");
x.put("number", 0);
Map<String, String> y = (Map<String, String>) (Object) x;
// This is fine
System.out.println(y.get("foo"));
// This goes bang! It's trying to cast an Integer to a String
System.out.println(y.get("number"));
}
}
So if you really want to avoid creating a new map, this "cast via Object" will work - but it's far from ideal.
Your approach is safer, although you can make it slightly more efficient by avoiding the lookup:
public static Map<String, String> copyToStringValueMap(
Map<String, Object> input) {
Map<String, String> ret = new HashMap<>();
for (Map.Entry<String, Object> entry : input.entrySet()) {
ret.put(entry.getKey(), (String) entry.getValue());
}
return ret;
}
A Java 8 solution:
private Map<String, String> stringifyValues(Map<String, Object> variables) {
return variables.entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey, e -> (String) e.getValue()));
}
Good solutions here, but I want to add another one that taking into consideration handling null values:
Map<String,Object> map = new HashMap<>();
Map<String,String> stringifiedMap = map.entrySet().stream()
.filter(m -> m.getKey() != null && m.getValue() !=null)
.collect(Collectors.toMap(Map.Entry::getKey, e -> (String)e.getValue()));
So I have a Map that has some values in it being passed into a method:
public String doThis(Map<String, ?> context){
.....
}
And I'm trying to insert an addition attribute to this Map
String abc="123";
context.put("newAttr",abc);
But I am getting this error:
The method put(String, capture#8-of ?) in the type Map is not applicable for the arguments (String, String)
Is there anyway to perform this put without "cloning" the Map?
If you want to put values of type X into a generic Map you need to declare the Map as Map<String, ? super X>. In your example X is String, so:
public String doThis(Map<String, ? super String> context){
.....
}
Map<String, ? super X> means: a map with keys of type String and values of a type which is X or a super-type of X. All such maps are ready to accept String instances as keys and X instances as values.
Remember PECS (Producer Extends, Consumer Super). You have a consumer (putting in), therefore it cannot be extends.
Surprisingly we can convert this map into an easier to use form. Just with this simiple syntax: (Map<String, ObjectOrSth>)unfriendlyMap.
// Let's get this weird map.
HashMap<String, String> mapOrig = new HashMap<String, String>();
Map<String, ?> mapQuestion = (Map<String, ?>)mapOrig;
//mapQuestion.put("key2", "?"); // impossible
// Convert it to almost anything...
Map<String, String> mapStr2 = (Map<String, String>)mapQuestion;
mapStr2.put("key2", "string2");
assertThat(mapOrig.get("key2")).isEqualTo("string2");
Map<String, Object> mapObj = (Map<String, Object>)mapQuestion;
mapObj.put("key3", "object");
assertThat(mapOrig.get("key3")).isEqualTo("object");
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>