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?
To insert the data in the map insert() function in the map is used. It is used to insert elements with a particular key in the map container. Parameters: It accepts a pair that consists of a key and element which is to be inserted into the map container but it only inserts the unique key.
A map is an associative container that maps keys to values, provides logarithmic complexity for inserting and finding, and constant time for erasing single elements. It is common for developers to use a map to keep track of objects by using a string key.
1. Add values to a Map. The standard solution to add values to a map is using the put() method, which associates the specified value with the specified key in the map. Note that if the map already contains a mapping corresponding to the specified key, the old value will be replaced by the specified value.
Convert a Map to a String Using Java Streams To perform conversion using streams, we first need to create a stream out of the available Map keys. Second, we're mapping each key to a human-readable String.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With