I have defined a collection using the type TreeMap< String, List < Pair < Integer, String >>> in which pair is a class that I defined:
public class Pair<L,R> {
private L l;
private R r;
public Pair(L l, R r) {
this.l = l;
this.r = r;
}
public L getL() {return l;}
public R getR() {return r;}
public void setL(L l){this.l = l;}
public void setR(R r){this.r = r;}
}
I want to return the string (TreeMap key) that is paired with a list that contains a given String value. For example, I have a String "bob" that is stored in one of the pairs in the list, and I want to return the key (string) of the Treemap that is associated with that list of pairs that "bob" is in. How would I go about doing this?
This essentially is a reverse lookup. You have a map
of keys associated to values and you want to find that key for which the associated value satisfies some condition. Note that this, in the worse case, will result in the entire table lookup which can be very expensive because you may end up accessing every entry in the map.
For starters, I'd do something very straightforward like below. I have taken liberty to modify the Pair
class a little bit. The following prints the key key2
as per your requirements:
public class ReverseLookup {
static class Pair<L,R> {
private L l;
private R r;
public Pair(L l, R r) {
this.l = l;
this.r = r;
}
public L getL() {return l;}
public R getR() {return r;}
public void setL(L l){this.l = l;}
public void setR(R r){this.r = r;}
public static <L, R> Pair<L, R> right(List<Pair<L, R>> pairs, R rVal) {
for (Pair<L, R> pair : pairs) {
if (rVal != null && rVal.equals(pair.getR()))
return pair;
}
return null;
}
}
public static void main(String[] args) {
String lookFor = "bob";
Map<String, List<Pair <Integer, String>>> listOfPairs = new TreeMap<>();
listOfPairs.put(
"key1", Arrays.asList(new Pair("2", "carol"), new Pair(4, "david"))
);
listOfPairs.put(
"key2", Arrays.asList(new Pair("0", "alice"), new Pair(1, "bob"))
);
for (Map.Entry<String, List<Pair<Integer, String>>> entry : listOfPairs.entrySet()) {
// entry is a mapping from string -> list of pairs Integer, String
List<Pair<Integer, String>> pairs = entry.getValue();
if (Pair.right(pairs, lookFor) != null) {
System.out.println(entry.getKey());
}
}
}
}