Advertisement
cesarnascimento

MapSimples

Nov 17th, 2017
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.92 KB | None | 0 0
  1. import java.util.HashMap;
  2. import java.util.Iterator;
  3. import java.util.Map;
  4. import java.util.Set;
  5.  
  6. public class MapSimples {
  7.  
  8.     public static void main(String[] args) {
  9.         Map<Object, String> mapAnimais = new HashMap<Object, String>();
  10.         //add os elementos no map por pares de chave-valor
  11.         mapAnimais.put(new Integer(2), "Coelho");
  12.         mapAnimais.put(new Integer(1), "Bode");
  13.         mapAnimais.put(new Integer(3), "Cachorro");
  14.         mapAnimais.put(new Integer(5), "Gato");
  15.         mapAnimais.put(new Integer(4), "Vaca");
  16.         // pegar o map pela interface Set para obter a chave e o valor
  17.         Set s = mapAnimais.entrySet(); //set ja tem o sort
  18.         //percorrer pelos pares(chave e valor) do Iterator pelo Map
  19.         Iterator it = s.iterator();
  20.         while(it.hasNext()) {
  21.             Map.Entry m = (Map.Entry) it.next();
  22.             int key = (Integer) m.getKey();
  23.             String value = (String) m.getValue();
  24.             System.out.println("Key: "+key+" Value: "+value);
  25.         }
  26.  
  27.     }
  28.  
  29. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement