gpt4 book ai didi

java - 实现数据结构和参数查询

转载 作者:行者123 更新时间:2023-12-01 23:40:55 24 4
gpt4 key购买 nike

我想创建这个数据限制:

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

关于java - 实现数据结构和参数查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58259783/

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