我想创建这个数据限制:
Map<String, Country> table = new HashMap<>();
table.put("AF", new Country("Afghanistan", "AFG", "004"));
// 300 more
class Country {
private String country;
private String alpha3;
private String number;
public Country(String country, String alpha3, String number) {
this.country = country;
this.alpha3 = alpha3;
this.number = number;
}
}
第二种方式:
Map<String, Country> table = new HashMap<>();
Table<String, String, Integer> table2 = HashBasedTable.create();
table.put("AF", HashBasedTable.create().put("Afghanistan", "AFG", "004"));
// 300 more
我想根据我发送的键将值搜索到数据结构值中:
- 国家/地区名称中的数字代码 国家
- 名称中的国家代码
- 来自国家名称的 alpha3 代码
在第二个数据结构中实现此搜索的最简单方法是什么?
HashMap
包含一个名为forEach(BiConsumer<? super K,? super V> action)
的方法,可用于循环访问HashMap
中的每个键值对。
因此,使用 lambda 您可以执行以下操作:
//Search a HashMap of employee ID/name records by name, for their ID number.
public int getID(HashMap<Integer, String> employees, String name) {
//Iterate through every key-value pair, performing the lambda's operation on it.
employees.forEach((Integer j, String k) -> {
if(k.equals(name)) return Integer.valueOf(j); //If the value matches the name, return the ID
}
return -1;
}