One of the possible workarounds is to work with a HashMap , which receives the key as 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 output will be:
{Sao paulo = Osasco}
It can be seen working in IDEONE
You can also create a separate class, which is responsible for manipulating this HashMap
. I made as basic an example as possible of what this class could be, just to illustrate how the construction would be:
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;
}
}
Your 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 at IDEONE .