Reputation: 1680
I have this multimap with Guava which I would like to implement with multiple maps in order to make key-value search:
String key = "first-key";
Multimap<String, String> map = ArrayListMultimap.create();
map.put(key, "firstValue");
map.put(key, "secondValue");
map.put(key, "thurdValue");
map.putAll("sec-key", Sets.newHashSet("am", "are", "is"));
for (String name : map.keySet()) {
System.out.println("key: " + name);
}
I tried this:
Map<String, String> map1 = new HashMap<String,String>();
Map<String, Map<String, String>> map2 = new HashMap<String, Map<String, String>>();
Map<String, Map<String, Map<String, String>>> map3 = new HashMap<String, Map<String, Map<String, String>>>();
map3.put("AF", Map.of("Afghanistan", Map.of("AFG", "004")));
How for example I can search for key Afghanistan
and get value AFG
?
Is there some better way to implement this?
Upvotes: 1
Views: 190
Reputation: 16498
I think using multimaps in your case unnecessarily complicates the task. Why don't you just define a class that stores all values and use a simple map?
Assuming that your example shows the ISO 3166 standard values for Afghanistan, I wold create a class country:
static class Country{
String name;
String alpha2;
String alpha3;
String numericCode;
public Country(String name, String alpha2, String alpha3, String numericCode) {
this.name = name;
this.alpha2 = alpha2;
this.alpha3 = alpha3;
this.numericCode = numericCode;
}
//getters and setters
}
and use a simple map Map<String, Country> myMap = new HashMap<>();
Map<String, Country> myMap = new HashMap<>();
myMap.put("AF", new Country("Afghanistan", "AF", "AFG", "004"));
myMap.put("IR", new Country("Iran", "IR", "IRN", "364"));
myMap.put("IN", new Country("India", "IN", "IND", "356"));
myMap.put("CN", new Country("China", "CN", "CHN", "156"));
To get the ALPHA_3 code for a search string "Afghanistan" for example
Optional<Country> search = myMap.values().stream().filter(c -> c.name.equals("Afghanistan")).findFirst();
System.out.println(search.isPresent()? search.get().getAlpha3(): "No results");
If you are interested in using a 3rd party library take a look at Javatuples
Using javatuples the upper one could be rewritten as follows
Map<String, Quartet> myMap = new HashMap<>();
myMap.put("AF", Quartet.with("Afghanistan", "AF", "AFG", "004"));
myMap.put("IR", Quartet.with("Iran", "IR", "IRN", "364"));
myMap.put("IN", Quartet.with("India", "IN", "IND", "356"));
myMap.put("CN", Quartet.with("China", "CN", "CHN", "156"));
Optional<Quartet> result = myMap.values().stream().filter(q -> q.contains("Afghanistan")).findFirst();
System.out.println(result.isPresent() ? result.get().getValue2():"No results");
Upvotes: 2