gpt4 book ai didi

java - 使用多个 map 实现搜索

转载 作者:行者123 更新时间:2023-11-30 01:45:18 26 4
gpt4 key购买 nike

我有一个带有 Guava 的多重映射,我想用多个映射来实现它,以便进行键值搜索:

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);
}

我尝试过这个:

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")));

例如,我如何搜索键 Afghanistan 并获取值 AFG

有没有更好的方法来实现这个?

最佳答案

我认为在您的情况下使用多重映射不必要地使任务复杂化。为什么不定义一个存储所有值的类并使用一个简单的映射?

假设您的示例显示阿富汗的 ISO 3166 标准值,我将创建一个国家/地区:

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
}

并使用简单的 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"));

获取搜索字符串“阿富汗”的 ALPHA_3 代码

Optional<Country> search = myMap.values().stream().filter(c -> c.name.equals("Afghanistan")).findFirst();
System.out.println(search.isPresent()? search.get().getAlpha3(): "No results");

如果您有兴趣使用第三方库,请查看 Javatuples

使用javatuples,上面的可以重写如下

   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");

关于java - 使用多个 map 实现搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58266765/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com