public String[] getValue(String keyName) {
ArrayList arraylist = (ArrayList) value.get(getKey(keyName));
String[] valueArray = new String[arraylist.size()];
for (int i = 0; i < valueArray.length; i++)
valueArray[i] = arraylist.get(i).toString();
return valueArray;
}
I want to modify this function to make it easier to use.
If the return String array contains only one element.I want it to be returned in String(not String array) type.
How can I do this in Java?
A project I worked on had to deal with something similar. There were some map-like objects. Each key had zero or more values. But there were some keys where we knew there was exactly one value. Others had at most one. Others had zero or more.
We addressed this by introducing an extension to
Collection:So essentially, we always returned a
Values<T>. If the caller knew there was just one value, it would simply useunique()orone()depending on whether no value was valid.For cases where the number of values were not important, we just kept values in the wrapped form.