Problema con HashMap

Iniciado por ferchundo9, 27 Diciembre 2017, 17:26 PM

0 Miembros y 1 Visitante están viendo este tema.

ferchundo9

Como podría iterar un hashmap y realizar eliminaciones de elementos del mismo dentro del bucle?

XafiloX

Mira la documentación sobre entrySet (https://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html#entrySet()).

CitarReturns a Set view of the mappings contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration over the set is in progress (except through the iterator's own remove operation, or through the setValue operation on a map entry returned by the iterator) the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll and clear operations. It does not support the add or addAll operations.

rub'n

#2
Testea  a ver  :xD
Código (java) [Seleccionar]
package testing.hashMap;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class HashMap_1 {

   private Map<String, Integer> hashMap = new HashMap<String,Integer>();

   public HashMap_1() {

       hashMap.put("prueba", 1);
       hashMap.put("prueba2", 2);

       println("Hash Map inicial");
       hashMap.forEach((key,valor) -> println("Key: "+key+" Valor: "+valor));

       //java 7
       for(Iterator<Map.Entry<String, Integer>> it = hashMap.entrySet().iterator(); it.hasNext(); ) {
           Map.Entry<String, Integer> entry = it.next();
           if(entry.getKey().equals("prueba2")) {
               it.remove();
           }
       }

       //java 8
       hashMap.keySet().removeIf(e -> (e.equals("prueba2")));
       hashMap.forEach((key,valor) -> println("Luego de Remover:\nkey "+key+" Valor: "+valor));

   }
   private static<T> void println(final T s){System.out.println(s);}
   public static void main(String ...aasas) {
       new HashMap_1();
   }
}



Salida en consola

Código (java) [Seleccionar]

Hash Map inicial
Key: prueba2 Valor: 2
Key: prueba Valor: 1
Luego de Remover:
key prueba Valor: 1

Process finished with exit code 0


rubn0x52.com KNOWLEDGE  SHOULD BE FREE!!!
If you don't have time to read, you don't have the time (or the tools) to write, Simple as that. Stephen