Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Key for two strings in a map?

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?

like image 886
IAdapter Avatar asked Feb 17 '11 09:02

IAdapter


4 Answers

Apache Commons Collections has MultiKey:

map.put(new MultiKey(key1, key2), value);

and a MultiKeyMap:

multiKeyMap.put(key1, key2, value);
like image 127
dogbane Avatar answered Oct 13 '22 19:10

dogbane


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.

like image 40
Vinay Lodha Avatar answered Oct 13 '22 19:10

Vinay Lodha


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.

like image 3
Gareth Davis Avatar answered Oct 13 '22 19:10

Gareth Davis


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.

like image 1
Johan Sjöberg Avatar answered Oct 13 '22 19:10

Johan Sjöberg