I need to create a map that has a key of two strings.
for example lets say
key = Name & Target
value = Permission(boolean)
Do I need to create a special object or is there any build in tuple in Java/Google Collections or Commons Collections or Commons Lang?
Apache Commons Collections has MultiKey:
map.put(new MultiKey(key1, key2), value);
and a MultiKeyMap:
multiKeyMap.put(key1, key2, value);
why dont you create a List
from those two Strings and use as a Key in Map
. It would keep the code more readable also.
You could cat the strings together but my personal preference is to create a little value object:
public class NameTarget {
private final String name;
private final String target;
public NameTarget(String name, String target){
this.name = name;
this.target = target;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((target == null) ? 0 : target.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
NameTarget other = (NameTarget) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (target == null) {
if (other.target != null)
return false;
} else if (!target.equals(other.target))
return false;
return true;
}
// add getters here
}
That took about 30 seconds to generate do in eclipse, it makes for a more type safe and cleaner code to work with in the long run.
You could and I have in the past created a Pair
style turple but I'm starting to prefer the named immutable value types for this sort of thing.
Is this what you're looking for?
String name = ...
String target = ...
String key = name + "_" + target;
map.put(key, value)
Alternatively you can create an object which hold two strings and override the hashCode
and equals
routines to differentiate in a better way than simple string concatenation.
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