Necesito iterar a través de un BucketMap y obtener todas las keys , pero ¿cómo llego a algo como buckets[i].next.next.next.key por ejemplo, sin hacerlo manualmente como lo intenté aquí?
public String[] getAllKeys() { //index of string array "allkeys" int j = 0; String allkeys[] = new String[8]; //iterates through the bucketmap for (int i = 0; i < buckets.length; i++) { //checks wether bucket has a key and value if (buckets[i] != null) { //adds key to allkeys allkeys[j] = buckets[i].key; // counts up the allkeys index after adding key j++; //checks wether next has a key and value if (buckets[i].next != null) { //adds key to allkeys allkeys[j] = buckets[i].next.key; j++; } } } return allkeys; } Además, ¿cómo puedo inicializar las teclas de String[] allkeys usando la versión de j que obtenemos después de que la iteración se realiza como índice?
Para la utilización básica, el HashMap es el mejor, he explicado cómo iterarlo, más fácil que usar un iterador:
public static void main (String[] args) { //a map with key type : String, value type : String Map<String,String> mp = new HashMap<String,String>(); mp.put("John","Math"); mp.put("Jack","Math"); map.put("Jeff","History"); //3 differents ways to iterate over the map for (String key : mp.keySet()){ //iterate over keys System.out.println(key+" "+mp.get(key)); } for (String value : mp.values()){ //iterate over values System.out.println(value); } for (Entry<String,String> pair : mp.entrySet()){ //iterate over the pairs System.out.println(pair.getKey()+" "+pair.getValue()); } }Una explicación rápida:
for (String name : mp.keySet()){ //Do Something }significa: "Para todas las cadenas de las claves del mapa, haremos algo, y en cada iteración llamaremos a la clave 'nombre' (puede ser lo que quieras, es una variable)
Aquí vamos :
public String[] getAllKeys(){ int i = 0; String allkeys[] = new String[buckets.length]; KeyValue val = buckets[i]; //Look at the first one if(val != null) { allkeys[i] = val.key; i++; } //Iterate until there is no next while(val.next != null){ allkeys[i] = val.next.key; val = val.next; i++; } return allkeys; }A ver si esto ayuda,
HashMap< String, String> map = new HashMap<>(); Set<String> keySet = map.keySet(); Iterator<String> iterator = keySet.iterator(); while(iterator.hasNext()) { //iterate over keys } //or iterate over entryset Iterator<Entry<String, String>> iterator2 = map.entrySet().iterator(); while(iterator2.hasNext()) { Entry<String, String> next = iterator2.next(); //get key next.getKey(); //get value next.getValue(); }Con Java 8, le sugiero que use Stream API.
Le permitirá iterar a través del Mapa en un enfoque mucho más conveniente:
public void iterateUsingStreamAPI(Map<String, Integer> map) { map.entrySet().stream() // ... .forEach(e -> System.out.println(e.getKey() + ":" + e.getValue())); }Busque más ejemplos sobre la iteración a través de mapas en Java .