Domanda

Posso scambiare le chiavi di due valori di un Hashmap o devo fare qualcosa di intelligente?

Qualcosa che assomiglierebbe a questo:

    Map.Entry<Integer, String> prev = null;
    for (Map.Entry<Integer, String> entry: collection.entrySet()) {
        if (prev != null) {
            if (entry.isBefore(prev)) {
                entry.swapWith(prev)
            }
        }
        prev = entry;
    }
È stato utile?

Soluzione

Bene, se stai cercando una mappa in cui sono ordinate le chiavi, usa una SortedMap invece.

SortedMap<Integer, String> map = new TreeMap<Integer, String>();

Puoi fare affidamento sull'ordinamento naturale della chiave (come in, la sua interfaccia Comparable ) oppure puoi fare un ordine personalizzato passando un Comparator .

In alternativa puoi chiamare setValue () su Entry .

Map.Entry<Integer, String> prev = null;
for (Map.Entry<Integer, String> entry: collection.entrySet()) {
  if (prev != null) {
    if (entry.isBefore(prev)) {
      String current = entry.getValue();
      entry.setValue(prev.getValue();
      prev.setValue(current);
    }
  }
  prev = entry;
}

Personalmente andrei semplicemente con una SortedMap .

Altri suggerimenti

Non c'è niente di simile nelle interfacce Map o Entry ma è abbastanza semplice da implementare:

    Map.Entry<Integer, String> prev = null;
    for (Map.Entry<Integer, String> entry: collection.entrySet()) {
            if (prev != null) {
                    if (entry.isBefore(prev)) {
                            swapValues(e, prev);
                    }
            }
            prev = entry;
    }

    private static <V> void swapValues(Map.Entry<?, V> first, Map.Entry<?, V> second)
    {
            first.setValue(second.setValue(first.getValue()));
    }
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top