jdk descargar actualizar java

java - descargar - ¿Cómo hacer para cada hashmap?



java descargar (7)

Lambda Expression Java 8

En Java 1.8 (Java 8), esto se ha vuelto mucho más fácil utilizando el método forEach de las operaciones agregadas ( operaciones de secuencia ) que se parece a los iteradores de la interfaz iterable .

Simplemente copie la declaración que se encuentra debajo de su código y cambie el nombre de la variable HashMap de hm a su variable HashMap para imprimir el par clave-valor.

HashMap<Integer,Integer> hm = new HashMap<Integer, Integer>(); /* * Logic to put the Key,Value pair in your HashMap hm */ // Print the key value pair in one line. hm.forEach((k,v) -> System.out.println("key: "+k+" value:"+v));

Aquí hay un ejemplo donde se usa una expresión Lambda :

HashMap<Integer,Integer> hm = new HashMap<Integer, Integer>(); Random rand = new Random(47); int i=0; while(i<5){ i++; int key = rand.nextInt(20); int value = rand.nextInt(50); System.out.println("Inserting key: "+key+" Value: "+value); Integer imap =hm.put(key,value); if( imap == null){ System.out.println("Inserted"); } else{ System.out.println("Replaced with "+imap); } } hm.forEach((k,v) -> System.out.println("key: "+k+" value:"+v)); Output: Inserting key: 18 Value: 5 Inserted Inserting key: 13 Value: 11 Inserted Inserting key: 1 Value: 29 Inserted Inserting key: 8 Value: 0 Inserted Inserting key: 2 Value: 7 Inserted key: 1 value:29 key: 18 value:5 key: 2 value:7 key: 8 value:0 key: 13 value:11

También se puede usar Spliterator para el mismo.

Spliterator sit = hm.entrySet().spliterator();

ACTUALIZAR

Incluyendo enlaces de documentación a Oracle Docs. Para obtener más información sobre Lambda, vaya a este link y debe leer Operaciones de agregados y para Spliterator vaya a este link .

Esta pregunta ya tiene una respuesta aquí:

Tengo este campo:

HashMap<String, HashMap> selects = new HashMap<String, HashMap>();

Para cada Hash<String, HashMap> necesito crear un ComboBox , cuyos elementos son el valor (que resulta ser un HashMap) de HashMap <String, **HashMap**> .

A modo de demostración (no funcional):

for (int i=0; i < selects.size(); i++) { HashMap h = selects[i].getValue(); ComboBox cb = new ComboBox(); for (int y=0; y < h.size(); i++) { cb.items.add(h[y].getValue); } }


Como ya se mencionó, en Java 8 tenemos el método forEach que acepta una link . Pero también tenemos APIs de stream .

Iterar sobre las entradas (usando forEach y Streams):

sample.forEach((k,v) -> System.out.println(k + "=" + v)); sample.entrySet().stream().forEachOrdered((entry) -> { Object currentKey = entry.getKey(); Object currentValue = entry.getValue(); System.out.println(currentKey + "=" + currentValue); }); sample.entrySet().parallelStream().forEach((entry) -> { Object currentKey = entry.getKey(); Object currentValue = entry.getValue(); System.out.println(currentKey + "=" + currentValue); });

La ventaja de los flujos es que se pueden paralelizar fácilmente y pueden ser útiles cuando tenemos varias CPU a disposición. Simplemente necesitamos usar parallelStream() en lugar de stream() arriba. Con flujos paralelos, tiene más sentido utilizar forEach ya que forEachOrdered no haría ninguna diferencia en el rendimiento. Si queremos iterar sobre las claves podemos usar sample.keySet() y para los valores sample.values() .

¿Por qué forEachOrdered y no forEach with streams?

Las forEach también proporcionan el método forEach , pero el comportamiento de forEach es explícitamente no determinista cuando el forEachOrdered realiza una acción para cada elemento de esta secuencia, en el orden de encuentro de la secuencia si la secuencia tiene un orden de encuentro definido. Así que forEach no garantiza que el pedido se mantenga. También compruebe this para más.


Generalmente hago lo mismo que cx42net, pero no creo explícitamente una Entrada.

HashMap<String, HashMap> selects = new HashMap<String, HashMap>(); for (String key : selects.keySet()) { HashMap<innerKey, String> boxHolder = selects.get(key); ComboBox cb = new ComboBox(); for (InnerKey innerKey : boxHolder.keySet()) { cb.items.add(boxHolder.get(innerKey)); } }

Esto me parece lo más intuitivo, creo que tengo prejuicios contra la iteración sobre los valores de un mapa.


Puede iterar sobre un HashMap (y muchas otras colecciones) usando un iterador, por ejemplo:

HashMap<T,U> map = new HashMap<T,U>(); ... Iterator it = map.values().iterator(); while (it.hasNext()) { System.out.println(it.next()); }


Sé que llego un poco tarde para eso, pero también compartiré lo que hice, en caso de que ayude a alguien más:

HashMap<String, HashMap> selects = new HashMap<String, HashMap>(); for(Map.Entry<String, HashMap> entry : selects.entrySet()) { String key = entry.getKey(); HashMap value = entry.getValue(); // do what you have to do here // In your case, another loop. }



Map.values() :

HashMap<String, HashMap<SomeInnerKeyType, String>> selects = new HashMap<String, HashMap<SomeInnerKeyType, String>>(); ... for(HashMap<SomeInnerKeyType, String> h : selects.values()) { ComboBox cb = new ComboBox(); for(String s : h.values()) { cb.items.add(s); } }