"Size or zero" of value of multivalued hashmap - java

I have a multivalued Hashmap (technically a LinkedHashMap):
private LinkedHashMap<String, ArrayList<BodyPart>> bodyParts = new LinkedHashMap<>();
I want to find the number of values associated with a given key. However, bodyParts.get("sample key") returns null if the key isn't present, whereas I want it to return 0 (as there are zero values associated with that key).
I could shield it in an if statement:
int numberOfValues;
if(bodyParts.containsKey("sample"){
numberOfValues = bodyParts.get("sample").size();
}
but I was wondering if there is an easier/better way to do it? I've read the documentation for computeIfPresent but, truthfully, didn't really understand it.

Use Map.getOrDefault(Object key, V defaultValue).
Returns the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key.

You can use getOrDefault method of Java Map interface.
It allows you to set default value that is to be returned in case value corresponding to key is not found. So in use case mentioned above you can use :
numberOfValues = bodyParts.getOrDefault("sample", new ArrayList<BodyPart>()).size();

Related

Freemarker - access value at a particular key in map

I have Map variable in my Freemarker template. How can I fetch a value at a particular key in the map, as we do in Java (map.get(<key>)).
I know how to iterate through keys and values of a map in a FTL. But I want a solution without iteration, on the lines of Java get() method of Map interface.
map[dynamicKey] or map.staticKey if the key is a string. Due to historical limitations, if the key isn't a string, map?api.get(nonStringKey).

Android HttpUrlConnection send multiple parameters with same key

How can i add multiple values with the same name in a HttpUrlConnection request.
example:
HashMap<String, String> params = new HashMap<>();
params.put("key[]", value1)
params.put("key[]", value2)
If i try to add multiple values with the same in postman i works fine, the application will send only one values (depends on request property, URLConnection setRequestProperty vs addRequestProperty).
I want to add both values as a parameter with the same name
This is not possible with Maps or HashMaps.
Taken from Oracles documentation on Maps:
http://docs.oracle.com/javase/7/docs/api/java/util/Map.html
An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value.
The put command will replace the previous value associated with the given key in the map (you can think of this like an array indexing operation for primitive types).
The Oracle Documentation for put states:
Associates the specified value with the specified key in this map. If
the map previously contained a mapping for the key, the old value is
replaced.
Returns the previous value associated with key, or null if there was
no mapping for key.
This can be found here:
http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html#put%28K,%20V%29
Alternatively You can do this and it will work fine.
You can make a JSONArray like this
JSONArray array = new JSONArray();
array.put("value1");
array.put("value2");
//and then you can send them as parameter like this-
params.put("key", array.toString());
It is not possible with params.put() But it is possible with params.add()
Reference : Difference between RequestParams add() and put() in AndroidAsyncHttp

Understanding String type MAP

Can some one explain the below code :
public Map<String, List<SubscriptionBean>> getSubscriptionInfo(DriverManagerDataSource ds, WebmartConfiguration webmartconnection, int publisherId, int setNo, InputDetails inputDetailsOb, ReportProperties repob, PublisherGeneralBean pubOb);
As i know map is pair of key and values. And in this scenario key are string type and object is List which is type of subscription bean. Please correct me if i m wrong.
Now i am unable to understand what does do getSubscriptionInfo ?
In all probability, it builds a map. The keys are strings, the values are lists of SubscriptionBeans. After it builds that map, it returns it.
But of course, the way to know that is to read the method's documentation.

JAVA - eclipse debug remove/change a key in map

I have a situation where I need to change(remove will also work) value corresponding to a key in a Map.
There are so many pairs in map. I don't want to copy all and create new map in change value for Map.
Is there any way I can directly change/remove value corresponding to a key.
I have tried changing complete map like :
Map m = commandParameters;
m.put("AID","");
return m;
But commandParameters is not resolved.
I tried changing that particular entry using random expressions, but could not work out.
Is there any way to do so?
**EDIT : ** commandParameters is original map.
Just do a remove on the map for a specific key.
commandParameters.remove("AID");
commandParameters.put("AID", "newvalue");
return commandParameters;

Whats the benefit of allowing multiple null keys in hashmap?

Just for experimenting, I added multiple null keys in a Hashmap instance. And it didn't complain. What's the benefit of doing that?
The code is,
Map hmap = new HashMap();
hmap.put("sushil","sushil11" );
hmap.put(null,null);
hmap.put(null,"king");
hmap.put(null,"nagasaki");
hmap.put(null,null);
How many keys are there in the map?
I would guess you haven't added multiple null-keys. You just overwrote the same nullkey multiple times.
A normal hashmap will have unique keys, so you're overwriting the entry for the null key repeatedly. You won't have multiple identical keys (for this you need a MultiMap or similar)
It is used to get switch:case:default behavior.
Example:
Problem Definition: Coffee shop in CS Department building. They provide coffee to CS Student for $1.00, to IT department students $1.25 and others for $1.50.
Then Map will be:
Key -> Value
IT -> 1.25
CS -> 1.00
null -> 1.50
if(map.containsKey(dept))
price = map.get(dept);
else
price = map.get(null);
P.S. - I am not "Department-ist" if that's a word. :)
There's an API call for this:
size: Returns the number of key-value mappings in this map.
hmap.size();
As noted you're just overwriting the key/value pair with a new value.
The question has asked about having multiple keys in HashMap which is not possible.
If you pass null again and again the old value is replaced only.
Refer:
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/HashMap.java#HashMap.putForNullKey%28java.lang.Object%29
HashMap allows multiple null values but only one null key.
If you write multiple null keys like below, then null will be overrides and you'll get the final overridden result. i.e "world"
Map<String, String> valueMap = new HashMap<>();
valueMap.put(null, "hello");
valueMap.put(null, "world");
System.out.println(valueMap.get(null));
Output:
"world"

Categories

Resources