Pergunta

Posso trocar as chaves de dois valores de um HashMap, ou eu preciso fazer alguma coisa inteligente?

Algo que seria algo parecido com isto:

    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;
    }
Foi útil?

Solução

Bem, se você está apenas depois de um mapa onde as chaves são ordenadas, use uma SortedMap .

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

Você pode contar com a ordem natural da chave (como, sua interface Comparable) ou você pode fazê-ordenação personalizada, passando um Comparator.

Como alternativa, você pode chamar setValue() na 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;
}

Pessoalmente, eu tinha acabado de ir com um SortedMap.

Outras dicas

Não há nada como que nos Map ou Entry as interfaces mas é muito simples de implementar:

    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()));
    }
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top