Come iterare in modo efficiente su ogni voce in una mappa Java?


Se ho un oggetto che implementa l'interfaccia Map in Java e desidero iterare su ogni coppia contenuta al suo interno, qual è il modo più efficiente di passare attraverso la mappa?

L'ordinamento degli elementi dipenderà dall'implementazione della mappa specifica che ho per l'interfaccia?

Author: Steve Chambers, 2008-09-06

30 answers

Map<String, String> map = ...
for (Map.Entry<String, String> entry : map.entrySet())
{
    System.out.println(entry.getKey() + "/" + entry.getValue());
}
 4195
Author: ScArcher2, 2016-01-26 20:37:37

Per riassumere le altre risposte e combinarle con quello che so, ho trovato 10 modi principali per farlo (vedi sotto). Inoltre, ho scritto alcuni test delle prestazioni (vedi risultati sotto). Ad esempio, se vogliamo trovare la somma di tutte le chiavi e i valori di una mappa, possiamo scrivere:

  1. Utilizzando iteratore e Mappa.Voce

    long i = 0;
    Iterator<Map.Entry<Integer, Integer>> it = map.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry<Integer, Integer> pair = it.next();
        i += pair.getKey() + pair.getValue();
    }
    
  2. Utilizzando foreach e Mappa.Voce

    long i = 0;
    for (Map.Entry<Integer, Integer> pair : map.entrySet()) {
        i += pair.getKey() + pair.getValue();
    }
    
  3. Utilizzando forEach da Java 8

    final long[] i = {0};
    map.forEach((k, v) -> i[0] += k + v);
    
  4. Utilizzando keySet e foreach

    long i = 0;
    for (Integer key : map.keySet()) {
        i += key + map.get(key);
    }
    
  5. Utilizzando Set di chiavi e iteratore

    long i = 0;
    Iterator<Integer> itr2 = map.keySet().iterator();
    while (itr2.hasNext()) {
        Integer key = itr2.next();
        i += key + map.get(key);
    }
    
  6. Utilizzando pere Mappa.Voce

    long i = 0;
    for (Iterator<Map.Entry<Integer, Integer>> entries = map.entrySet().iterator(); entries.hasNext(); ) {
        Map.Entry<Integer, Integer> entry = entries.next();
        i += entry.getKey() + entry.getValue();
    }
    
  7. Utilizzo dell'API di flusso Java 8

    final long[] i = {0};
    map.entrySet().stream().forEach(e -> i[0] += e.getKey() + e.getValue());
    
  8. Utilizzo di Java 8 Stream API parallel

    final long[] i = {0};
    map.entrySet().stream().parallel().forEach(e -> i[0] += e.getKey() + e.getValue());
    
  9. Utilizzando IterableMap di Apache Collections

    long i = 0;
    MapIterator<Integer, Integer> it = iterableMap.mapIterator();
    while (it.hasNext()) {
        i += it.next() + it.getValue();
    }
    
  10. Utilizzo di MutableMap delle collezioni Eclipse (CS)

    final long[] i = {0};
    mutableMap.forEachKeyValue((key, value) -> {
        i[0] += key + value;
    });
    

Test di perfomance (mode = AverageTime, system = Windows 8.1 64-bit, Intel i7-4790 3.60 GHz, 16 GB)

  1. Per la mappa piccola (100 elementi), il punteggio 0.308 è il migliore

    Benchmark                          Mode  Cnt  Score    Error  Units
    test3_UsingForEachAndJava8         avgt  10   0.308 ±  0.021  µs/op
    test10_UsingEclipseMap             avgt  10   0.309 ±  0.009  µs/op
    test1_UsingWhileAndMapEntry        avgt  10   0.380 ±  0.014  µs/op
    test6_UsingForAndIterator          avgt  10   0.387 ±  0.016  µs/op
    test2_UsingForEachAndMapEntry      avgt  10   0.391 ±  0.023  µs/op
    test7_UsingJava8StreamApi          avgt  10   0.510 ±  0.014  µs/op
    test9_UsingApacheIterableMap       avgt  10   0.524 ±  0.008  µs/op
    test4_UsingKeySetAndForEach        avgt  10   0.816 ±  0.026  µs/op
    test5_UsingKeySetAndIterator       avgt  10   0.863 ±  0.025  µs/op
    test8_UsingJava8StreamApiParallel  avgt  10   5.552 ±  0.185  µs/op
    
  2. Per la mappa con 10000 elementi, il punteggio 37.606 è il migliore

    Benchmark                           Mode   Cnt  Score      Error   Units
    test10_UsingEclipseMap              avgt   10    37.606 ±   0.790  µs/op
    test3_UsingForEachAndJava8          avgt   10    50.368 ±   0.887  µs/op
    test6_UsingForAndIterator           avgt   10    50.332 ±   0.507  µs/op
    test2_UsingForEachAndMapEntry       avgt   10    51.406 ±   1.032  µs/op
    test1_UsingWhileAndMapEntry         avgt   10    52.538 ±   2.431  µs/op
    test7_UsingJava8StreamApi           avgt   10    54.464 ±   0.712  µs/op
    test4_UsingKeySetAndForEach         avgt   10    79.016 ±  25.345  µs/op
    test5_UsingKeySetAndIterator        avgt   10    91.105 ±  10.220  µs/op
    test8_UsingJava8StreamApiParallel   avgt   10   112.511 ±   0.365  µs/op
    test9_UsingApacheIterableMap        avgt   10   125.714 ±   1.935  µs/op
    
  3. Per la mappa con 100000 elementi, il punteggio 1184.767 è il migliore

    Benchmark                          Mode   Cnt  Score        Error    Units
    test1_UsingWhileAndMapEntry        avgt   10   1184.767 ±   332.968  µs/op
    test10_UsingEclipseMap             avgt   10   1191.735 ±   304.273  µs/op
    test2_UsingForEachAndMapEntry      avgt   10   1205.815 ±   366.043  µs/op
    test6_UsingForAndIterator          avgt   10   1206.873 ±   367.272  µs/op
    test8_UsingJava8StreamApiParallel  avgt   10   1485.895 ±   233.143  µs/op
    test5_UsingKeySetAndIterator       avgt   10   1540.281 ±   357.497  µs/op
    test4_UsingKeySetAndForEach        avgt   10   1593.342 ±   294.417  µs/op
    test3_UsingForEachAndJava8         avgt   10   1666.296 ±   126.443  µs/op
    test7_UsingJava8StreamApi          avgt   10   1706.676 ±   436.867  µs/op
    test9_UsingApacheIterableMap       avgt   10   3289.866 ±  1445.564  µs/op
    

Grafici (test di perfomance in base alle dimensioni della mappa)

Inserisci qui la descrizione dell'immagine

Tabella (test di perfomance in base alle dimensioni della mappa)

          100     600      1100     1600     2100
test10    0.333    1.631    2.752    5.937    8.024
test3     0.309    1.971    4.147    8.147   10.473
test6     0.372    2.190    4.470    8.322   10.531
test1     0.405    2.237    4.616    8.645   10.707
test2     0.376    2.267    4.809    8.403   10.910
test7     0.473    2.448    5.668    9.790   12.125
test9     0.565    2.830    5.952   13.220   16.965
test4     0.808    5.012    8.813   13.939   17.407
test5     0.810    5.104    8.533   14.064   17.422
test8     5.173   12.499   17.351   24.671   30.403

Tutti i test sono su GitHub .

 750
Author: Viacheslav Vedenin, 2018-04-10 21:44:37

In Java 8 puoi farlo in modo pulito e veloce usando le nuove funzionalità lambda:

 Map<String,String> map = new HashMap<>();
 map.put("SomeKey", "SomeValue");
 map.forEach( (k,v) -> [do something with key and value] );

 // such as
 map.forEach( (k,v) -> System.out.println("Key: " + k + ": Value: " + v));

Il tipo di k e v verrà dedotto dal compilatore e non è più necessario utilizzare Map.Entry.

Facile-peasy!

 231
Author: Austin Powers, 2016-09-07 08:33:17

Sì, l'ordine dipende dall'implementazione specifica della mappa.

@ScArcher2 ha la sintassi Java 1.5 più elegante . In 1.4, farei qualcosa del genere:

Iterator entries = myMap.entrySet().iterator();
while (entries.hasNext()) {
  Entry thisEntry = (Entry) entries.next();
  Object key = thisEntry.getKey();
  Object value = thisEntry.getValue();
  // ...
}
 201
Author: pkaeding, 2018-02-06 22:32:29

Il codice tipico per l'iterazione su una mappa è:

Map<String,Thing> map = ...;
for (Map.Entry<String,Thing> entry : map.entrySet()) {
    String key = entry.getKey();
    Thing thing = entry.getValue();
    ...
}

HashMap è l'implementazione della mappa canonica e non fornisce garanzie (o anche se non dovrebbe cambiare l'ordine se non viene eseguita alcuna operazione di mutazione su di esso). SortedMap restituirà le voci in base all'ordinamento naturale delle chiavi, o a Comparator, se fornito. LinkedHashMap restituirà le voci in ordine di inserimento o ordine di accesso a seconda di come è stato costruito. EnumMap restituisce le voci in ordine naturale di chiave.

(Aggiornamento: penso che questo non sia più vero.) Nota, IdentityHashMap entrySet iterator ha attualmente un'implementazione peculiare che restituisce la stessa istanza Map.Entry per ogni elemento nel entrySet! Tuttavia, ogni volta che un nuovo iteratore avanza il Map.Entry viene aggiornato.

 103
Author: Tom Hawtin - tackline, 2018-02-09 01:11:36

Esempio di utilizzo di iteratore e generici:

Iterator<Map.Entry<String, String>> entries = myMap.entrySet().iterator();
while (entries.hasNext()) {
  Map.Entry<String, String> entry = entries.next();
  String key = entry.getKey();
  String value = entry.getValue();
  // ...
}
 91
Author: serg, 2009-08-18 17:34:51

Questa è una domanda in due parti:

Come iterare le voci di una mappa - @ScArcher2 ha risposto perfettamente.

Qual è l'ordine di iterazione - se stai solo usando Map, quindi in senso stretto, non ci sono garanzie di ordine. Quindi non dovresti davvero fare affidamento sull'ordine dato da qualsiasi implementazione. Tuttavia, il SortedMap interfaccia estende Map e fornisce esattamente quello che stai cercando - le implementazioni forniranno un ordinamento coerente.

NavigableMap è un'altra estensione utile - questo è un SortedMap con metodi aggiuntivi per trovare le voci in base alla loro posizione ordinata nel set di chiavi. Quindi potenzialmente questo può rimuovere la necessità di iterare in primo luogo-potresti essere in grado di trovare lo specifico entry che stai dopo aver usato higherEntry, lowerEntry, ceilingEntry, o floorEntry metodi. Il metodo descendingMap fornisce anche un metodo esplicito di che inverte il ordine di attraversamento.

 78
Author: serg10, 2017-05-23 11:47:32

Esistono diversi modi per scorrere la mappa.

Ecco il confronto delle loro prestazioni per un set di dati comune memorizzato in map memorizzando un milione di coppie di valori chiave in map e itererà su map.

1) Utilizzo di entrySet() in per ogni ciclo

for (Map.Entry<String,Integer> entry : testMap.entrySet()) {
    entry.getKey();
    entry.getValue();
}

50 millisecondi

2) Utilizzo di keySet() in per ogni ciclo

for (String key : testMap.keySet()) {
    testMap.get(key);
}

76 millisecondi

3) Utilizzo di entrySet() e iteratore

Iterator<Map.Entry<String,Integer>> itr1 = testMap.entrySet().iterator();
while(itr1.hasNext()) {
    Map.Entry<String,Integer> entry = itr1.next();
    entry.getKey();
    entry.getValue();
}

50 millisecondi

4) Utilizzo di keySet() e iteratore

Iterator itr2 = testMap.keySet().iterator();
while(itr2.hasNext()) {
    String key = itr2.next();
    testMap.get(key);
}

75 millisecondi

Ho fatto riferimento this link.

 63
Author: Darshan Patel, 2015-07-18 15:58:26

CORDIALI saluti, puoi anche usare map.keySet() e map.values() se sei interessato solo alle chiavi/valori della mappa e non all'altro.

 43
Author: ckpwong, 2008-09-05 22:27:52

Il modo corretto per farlo è usare la risposta accettata in quanto è la più efficiente. Trovo che il seguente codice sia un po ' più pulito.

for (String key: map.keySet()) {
   System.out.println(key + "/" + map.get(key));
}
 42
Author: Chris Dail, 2011-10-17 00:16:44

Con Eclipse Collections (precedentemente GS Collections ), si utilizza il metodo forEachKeyValue sull'interfaccia MapIterable , ereditata dalle interfacce MutableMap e ImmutableMap e dalle relative implementazioni.

final MutableBag<String> result = Bags.mutable.empty();
MutableMap<Integer, String> map = Maps.mutable.of(1, "One", 2, "Two", 3, "Three");
map.forEachKeyValue(new Procedure2<Integer, String>()
{
    public void value(Integer key, String value)
    {
        result.add(key + value);
    }
});
Assert.assertEquals(Bags.mutable.of("1One", "2Two", "3Three"), result);

Con Java 8 lambda sintassi, è possibile scrivere il codice come segue:

MutableBag<String> result = Bags.mutable.empty();
MutableMap<Integer, String> map = Maps.mutable.of(1, "One", 2, "Two", 3, "Three");
map.forEachKeyValue((key, value) -> result.add(key + value));
Assert.assertEquals(Bags.mutable.of("1One", "2Two", "3Three"), result);

Nota: Sono un committer per le collezioni Eclipse.

 23
Author: Donald Raab, 2018-09-13 01:25:34

Prova questo con Java 1.4:

for( Iterator entries = myMap.entrySet().iterator(); entries.hasNext();){

  Entry entry = (Entry) entries.next();

  System.out.println(entry.getKey() + "/" + entry.getValue());

  //...
}
 20
Author: abods, 2013-06-07 14:34:44

In teoria, il modo più efficiente dipenderà da quale implementazione di Map. Il modo ufficiale per farlo è chiamare map.entrySet(), che restituisce un insieme di Map.Entry, ognuno dei quali contiene una chiave e un valore (entry.getKey() e entry.getValue()).

In un'implementazione idiosincratica, potrebbe fare qualche differenza se si utilizza map.keySet(), map.entrySet() o qualcos'altro. Ma non riesco a pensare a un motivo per cui qualcuno dovrebbe scriverlo in quel modo. Molto probabilmente non fa differenza per le prestazioni quello che fai.

E sì, l'ordine dipenderà dall'implementazione, nonché (possibilmente) dall'ordine di inserimento e da altri fattori difficili da controllare.

[modifica] Ho scritto valueSet() in origine ma ovviamente entrySet() è in realtà la risposta.

 20
Author: Leigh Caldwell, 2017-05-04 22:39:46

Java 8:

Puoi usare espressioni lambda:

myMap.entrySet().stream().forEach((entry) -> {
    Object currentKey = entry.getKey();
    Object currentValue = entry.getValue();
});

Per ulteriori informazioni, seguire questo.

 20
Author: George Siggouroglou, 2018-02-06 03:37:46

Lambda Espressione Java 8

In Java 1.8 (Java 8) questo è diventato molto più semplice utilizzando forEachmetodo da operazioni aggregate( Operazioni di flusso) che sembra simile a iteratori da Iterabile Interfaccia.

Basta copiare incolla sotto l'istruzione nel codice e rinominare la variabile HashMap da hm alla variabile HashMap per stampare la coppia chiave-valore.

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));

// Just copy and paste above line to your code.

Di seguito è riportato il codice di esempio che ho provato utilizzando Espressione Lambda . Questa roba è così cool. Devo provarci.

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

Anche uno può usare Spliterator per lo stesso.

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

AGGIORNAMENTO


Compresi i collegamenti alla documentazione di Oracle Docs. Per ulteriori informazioni su Lambda vai a questo link e devi leggere Operazioni aggregate e per Spliterator vai a questo link .

 17
Author: Nitin Mahesh, 2016-03-16 15:38:05

Nella mappa si può iterare su keys e / o values e / o both (e.g., entrySet) dipende dal proprio interesse in_ Come:

1.) Iterare attraverso il keys -> keySet() della mappa:

Map<String, Object> map = ...;

for (String key : map.keySet()) {
    //your Business logic...
}

2.) Iterare attraverso il values -> values() della mappa:

for (Object value : map.values()) {
    //your Business logic...
}

3.) Iterare attraverso il both -> entrySet() della mappa:

for (Map.Entry<String, Object> entry : map.entrySet()) {
    String key = entry.getKey();
    Object value = entry.getValue();
    //your Business logic...
}

Inoltre, ci sono 3 modi diversi per iterare attraverso una HashMap. Sono come sotto _

//1.
for (Map.Entry entry : hm.entrySet()) {
    System.out.print("key,val: ");
    System.out.println(entry.getKey() + "," + entry.getValue());
}

//2.
Iterator iter = hm.keySet().iterator();
while(iter.hasNext()) {
    Integer key = (Integer)iter.next();
    String val = (String)hm.get(key);
    System.out.println("key,val: " + key + "," + val);
}

//3.
Iterator it = hm.entrySet().iterator();
while (it.hasNext()) {
    Map.Entry entry = (Map.Entry) it.next();
    Integer key = (Integer)entry.getKey();
    String val = (String)entry.getValue();
    System.out.println("key,val: " + key + "," + val);
}
 16
Author: Rupesh Yadav, 2014-01-29 12:35:03
public class abcd{
    public static void main(String[] args)
    {
       Map<Integer, String> testMap = new HashMap<Integer, String>();
        testMap.put(10, "a");
        testMap.put(20, "b");
        testMap.put(30, "c");
        testMap.put(40, "d");
        for (Integer key:testMap.keySet()) {
            String value=testMap.get(key);
            System.out.println(value);
        }
    }
}

O

public class abcd {
    public static void main(String[] args)
    {
       Map<Integer, String> testMap = new HashMap<Integer, String>();
        testMap.put(10, "a");
        testMap.put(20, "b");
        testMap.put(30, "c");
        testMap.put(40, "d");
        for (Entry<Integer, String> entry : testMap.entrySet()) {
            Integer key=entry.getKey();
            String value=entry.getValue();
        }
    }
}
 15
Author: Fathah Rehman P, 2013-06-07 14:34:13

Se si dispone di una mappa generica non tipizzata è possibile utilizzare:

Map map = new HashMap();
for (Map.Entry entry : ((Set<Map.Entry>) map.entrySet())) {
    System.out.println(entry.getKey() + "/" + entry.getValue());
}
 14
Author: dmunozfer, 2016-03-16 16:17:58

Con Java 8

map.forEach((k, v) -> System.out.println((k + ":" + v)));
 13
Author: Taras Melnyk, 2018-05-03 11:25:07

Più compatto con Java 8:

map.entrySet().forEach(System.out::println);
 12
Author: bluehallu, 2018-04-19 12:32:20
    Iterator iterator = map.entrySet().iterator();
    while (iterator.hasNext()) {
        Map.Entry element = (Map.Entry)it.next();
        LOGGER.debug("Key: " + element.getKey());
        LOGGER.debug("value: " + element.getValue());    
    }
 10
Author: Fadid, 2016-01-14 20:58:30

Puoi farlo usando i generici:

Map<Integer, Integer> map = new HashMap<Integer, Integer>();
Iterator<Map.Entry<Integer, Integer>> entries = map.entrySet().iterator();
while (entries.hasNext()) {
    Map.Entry<Integer, Integer> entry = entries.next();
    System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
 8
Author: Pranoti, 2016-03-16 15:54:24
Iterator itr2 = testMap.keySet().iterator();
while (itr2.hasNext()) {
    String key = itr2.next();
    testMap.get(key);
}

for (String key: map.keySet()) {    
    System.out.println(key + "/" + map.get(key)); 
}

Il modo migliore è entrySet() però.

 7
Author: Debaprasad, 2014-09-24 11:37:45

In Java 8 abbiamo il metodo forEachche accetta un'espressione lambda . Abbiamo anche stream API. Considera una mappa:

Map<String,String> sample = new HashMap<>();
sample.put("A","Apple");
sample.put("B", "Ball");

Itera le chiavi:

sample.keySet().forEach((k) -> System.out.println(k));

Itera sui valori:

sample.values().forEach((v) -> System.out.println(v));

Itera le voci (usando forEach e Stream):

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

Il vantaggio con i flussi è che possono essere parallelizzati facilmente nel caso in cui lo vogliamo. Abbiamo semplicemente bisogno di usare parallelStream() al posto di stream() sopra.

 6
Author: i_am_zero, 2015-09-02 01:13:29
           //Functional Oprations
            Map<String, String> mapString = new HashMap<>();
            mapString.entrySet().stream().map((entry) -> {
                String mapKey = entry.getKey();
                return entry;
            }).forEach((entry) -> {
                String mapValue = entry.getValue();
            });

            //Intrator
            Map<String, String> mapString = new HashMap<>();
            for (Iterator<Map.Entry<String, String>> it = mapString.entrySet().iterator(); it.hasNext();) {
                Map.Entry<String, String> entry = it.next();
                String mapKey = entry.getKey();
                String mapValue = entry.getValue();
            }

            //Simple for loop
            Map<String, String> mapString = new HashMap<>();
            for (Map.Entry<String, String> entry : mapString.entrySet()) {
                String mapKey = entry.getKey();
                String mapValue = entry.getValue();

            }
 6
Author: Sajad NasiriNezhad, 2016-04-13 07:47:46
package com.test;

import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class Test {

    public static void main(String[] args) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("ram", "ayodhya");
        map.put("krishan", "mathura");
        map.put("shiv", "kailash");

        System.out.println("********* Keys *********");
        Set<String> keys = map.keySet();
        for (String key : keys) {
            System.out.println(key);
        }

        System.out.println("********* Values *********");
        Collection<String> values = map.values();
        for (String value : values) {
            System.out.println(value);
        }

        System.out.println("***** Keys and Values (Using for each loop) *****");
        for (Map.Entry<String, String> entry : map.entrySet()) {
            System.out.println("Key: " + entry.getKey() + "\t Value: "
                    + entry.getValue());
        }

        System.out.println("***** Keys and Values (Using while loop) *****");
        Iterator<Entry<String, String>> entries = map.entrySet().iterator();
        while (entries.hasNext()) {
            Map.Entry<String, String> entry = (Map.Entry<String, String>) entries
                    .next();
            System.out.println("Key: " + entry.getKey() + "\t Value: "
                    + entry.getValue());
        }

        System.out
                .println("** Keys and Values (Using java 8 using lambdas )***");
        map.forEach((k, v) -> System.out
                .println("Key: " + k + "\t value: " + v));
    }
}
 6
Author: Rupendra Sharma, 2017-04-06 06:36:15

Sì, come molte persone hanno convenuto che questo è il modo migliore per iterare su un Map.

Ma ci sono possibilità di lanciare nullpointerexception se la mappa è null. Non dimenticare di mettere null.check-in.

                                                 |
                                                 |
                                         - - - -
                                       |
                                       |
for (Map.Entry<String, Object> entry : map.entrySet()) {
    String key = entry.getKey();
    Object value = entry.getValue();
}
 6
Author: ꜱᴜʀᴇꜱʜ ᴀᴛᴛᴀ, 2018-02-06 22:40:17

Ci sono molti modi per farlo. Di seguito sono riportati alcuni semplici passaggi:

Supponiamo di avere una mappa come:

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

Quindi puoi fare qualcosa come il seguente per scorrere gli elementi della mappa.

// ********** Using an iterator ****************
Iterator<Entry<String, Integer>> me = m.entrySet().iterator();
while(me.hasNext()){
    Entry<String, Integer> pair = me.next();
    System.out.println(pair.getKey() + ":" + pair.getValue());
}

// *********** Using foreach ************************
for(Entry<String, Integer> me : m.entrySet()){
    System.out.println(me.getKey() + " : " + me.getValue());
}

// *********** Using keySet *****************************
for(String s : m.keySet()){
    System.out.println(s + " : " + m.get(s));
}

// *********** Using keySet and iterator *****************
Iterator<String> me = m.keySet().iterator();
while(me.hasNext()){
    String key = me.next();
    System.out.println(key + " : " + m.get(key));
}
 6
Author: Utpal Kumar, 2018-03-22 10:10:05

Usa Java 8:

map.entrySet().forEach(entry -> System.out.println(entry.getValue()));
 6
Author: ABHAY JOHRI, 2018-04-17 19:03:40

L'ordine dipenderà sempre dall'implementazione specifica della mappa. Usando Java 8 puoi usare uno di questi:

map.forEach((k,v) -> { System.out.println(k + ":" + v); });

Oppure:

map.entrySet().forEach((e) -> {
            System.out.println(e.getKey() + " : " + e.getValue());
        });

Il risultato sarà lo stesso (stesso ordine). L'entrySet sostenuto dalla mappa in modo da ottenere lo stesso ordine. Il secondo è utile in quanto consente di utilizzare lambda, ad esempio se si desidera stampare solo oggetti interi maggiori di 5:

map.entrySet()
    .stream()
    .filter(e-> e.getValue() > 5)
    .forEach(System.out::println);

Il codice seguente mostra l'iterazione tramite LinkedHashMap e HashMap normale (esempio). Vedrai la differenza nell'ordine:

public class HMIteration {


    public static void main(String[] args) {
        Map<Object, Object> linkedHashMap = new LinkedHashMap<>();
        Map<Object, Object> hashMap = new HashMap<>();

        for (int i=10; i>=0; i--) {
            linkedHashMap.put(i, i);
            hashMap.put(i, i);
        }

        System.out.println("LinkedHashMap (1): ");
        linkedHashMap.forEach((k,v) -> { System.out.print(k + " (#="+k.hashCode() + "):" + v + ", "); });

        System.out.println("\nLinkedHashMap (2): ");

        linkedHashMap.entrySet().forEach((e) -> {
            System.out.print(e.getKey() + " : " + e.getValue() + ", ");
        });


        System.out.println("\n\nHashMap (1): ");
        hashMap.forEach((k,v) -> { System.out.print(k + " (#:"+k.hashCode() + "):" + v + ", "); });

        System.out.println("\nHashMap (2): ");

        hashMap.entrySet().forEach((e) -> {
            System.out.print(e.getKey() + " : " + e.getValue() + ", ");
        });
    }
}

LinkedHashMap (1):

10 (#=10):10, 9 (#=9):9, 8 (#=8):8, 7 (#=7):7, 6 (#=6):6, 5 (#=5):5, 4 (#=4):4, 3 (#=3):3, 2 (#=2):2, 1 (#=1):1, 0 (#=0):0,

LinkedHashMap (2):

10 : 10, 9 : 9, 8 : 8, 7 : 7, 6 : 6, 5 : 5, 4 : 4, 3 : 3, 2 : 2, 1 : 1, 0 : 0,

HashMap (1):

0 (#:0):0, 1 (#:1):1, 2 (#:2):2, 3 (#:3):3, 4 (#:4):4, 5 (#:5):5, 6 (#:6):6, 7 (#:7):7, 8 (#:8):8, 9 (#:9):9, 10 (#:10):10,

HashMap (2):

0 : 0, 1 : 1, 2 : 2, 3 : 3, 4 : 4, 5 : 5, 6 : 6, 7 : 7, 8 : 8, 9 : 9, 10 : 10,

 5
Author: Witold Kaczurba, 2018-03-22 10:12:23