One of the possible solutions is to work with a Hashmap, that receives as key the code, and other HashMap
as value, where you will save the state-city pair.
public class MapTest {
public static void main(String[] args) {
//map principal
Map<Integer, HashMap<String, String>> codeStateList = new HashMap<>();
//cria um map para cruzar estado cidade
HashMap<String, String> stateCity = new HashMap<>();
//adiciona o par estado cidade
stateCity.put("Sao paulo", "Osasco");
//salva no map principal o code cruzando com map com par estado-cidade
codeStateList.put(1253, stateCity);
//para exibir ou pegar o par
System.out.println(codeStateList.get(1253));
}
}
The exit will be:
{Sao paulo=Osasco}
Can be seen working on IDEONE
You can also crack a class by itself, which is responsible for manipulating this HashMap
. I made an example as basic as possible of what this class might look like, just to illustrate what the construction would be like:
class StateCityMap {
private final Map<Integer, HashMap<String, String>> codeStateList;
public StateCityMap() {
codeStateList = new HashMap<>();
}
public void putStateCity(int code, String state, String city) {
HashMap<String, String> stateCity = new HashMap<>();
stateCity.put(state, city);
codeStateList.put(code, stateCity);
}
public String getStateCity(int key) {
return this.containsKey(key) ? codeStateList.get(key).toString() : null;
}
public void removeStateCity(int key) {
for (Iterator<Map.Entry<Integer, HashMap<String, String>>> iterator = codeStateList.entrySet().iterator(); iterator.hasNext();) {
Map.Entry<Integer, HashMap<String, String>> entry = iterator.next();
if (entry.getKey().equals(key)) {
iterator.remove();
}
}
}
public boolean containsKey(int key) {
return codeStateList.containsKey(key);
}
public String showAllItens() {
String allItens = "";
for (Map.Entry<Integer, HashMap<String, String>> entry : codeStateList.entrySet()) {
allItens += entry.getKey() + " : " + entry.getValue() + "\n";
}
return allItens;
}
}
Its use:
public class StateCityClassTest {
public static void main(String[] args) {
StateCityMap map = new StateCityMap();
map.putStateCity(1253, "São Paulo", "Osasco");
map.putStateCity(1254, "São Paulo", "Santos");
map.putStateCity(1255, "Rio de Janeiro", "Cabo Frio");
System.out.println(map.getStateCity(1253));
System.out.println(map.showAllItens());
}
}
See working on IDEONE.
Has any response helped solve the problem and can address similar questions from other users? If so, make sure to mark the answer as accepted. To do this just click on the left side of it (below the indicator of up and down votes).
– Sorack