Foro de elhacker.net

Programación => Java => Mensaje iniciado por: ferchundo9 en 27 Diciembre 2017, 17:26 pm



Título: Problema con HashMap
Publicado por: ferchundo9 en 27 Diciembre 2017, 17:26 pm
Como podría iterar un hashmap y realizar eliminaciones de elementos del mismo dentro del bucle?


Título: Re: Problema con HashMap
Publicado por: XafiloX en 27 Diciembre 2017, 18:46 pm
Mira la documentación sobre entrySet (https://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html#entrySet() (https://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html#entrySet())).

Citar
Returns 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.


Título: Re: Problema con HashMap
Publicado por: rub'n en 28 Diciembre 2017, 21:16 pm
Testea  a ver  :xD
Código
  1. package testing.hashMap;
  2.  
  3. import java.util.HashMap;
  4. import java.util.Iterator;
  5. import java.util.Map;
  6.  
  7. public class HashMap_1 {
  8.  
  9.    private Map<String, Integer> hashMap = new HashMap<String,Integer>();
  10.  
  11.    public HashMap_1() {
  12.  
  13.        hashMap.put("prueba", 1);
  14.        hashMap.put("prueba2", 2);
  15.  
  16.        println("Hash Map inicial");
  17.        hashMap.forEach((key,valor) -> println("Key: "+key+" Valor: "+valor));
  18.  
  19.        //java 7
  20.        for(Iterator<Map.Entry<String, Integer>> it = hashMap.entrySet().iterator(); it.hasNext(); ) {
  21.            Map.Entry<String, Integer> entry = it.next();
  22.            if(entry.getKey().equals("prueba2")) {
  23.                it.remove();
  24.            }
  25.        }
  26.  
  27.        //java 8
  28.        hashMap.keySet().removeIf(e -> (e.equals("prueba2")));
  29.        hashMap.forEach((key,valor) -> println("Luego de Remover:\nkey "+key+" Valor: "+valor));
  30.  
  31.    }
  32.    private static<T> void println(final T s){System.out.println(s);}
  33.    public static void main(String ...aasas) {
  34.        new HashMap_1();
  35.    }
  36. }
  37.  
  38.  

Salida en consola

Código
  1. Hash Map inicial
  2. Key: prueba2 Valor: 2
  3. Key: prueba Valor: 1
  4. Luego de Remover:
  5. key prueba Valor: 1
  6.  
  7. Process finished with exit code 0
  8.