Jump to content

Percorer HashMap


shurtup
 Share

Recommended Posts

como eu percorro o meu hashmap até encontrar o CPF 111.111.222-33 com o método getCpf.

ao achar, imprime "encontrei"

Se não achar, imprime "não encontrei"

com a collection array list eu consegui.

for(Pessoa p: nomes) {
 if (p.getCpf() == "111.222.333-44") {
   System.out.println("Encontrei");
 break;
 }
 else
 System.out.println("não ncontrei");

}

como faço com hashmap? segue código abaixo

package exercicio5;

import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;

public class TestePessoaMapa {

public static void main(String[] args) {

   HashMap<String, Pessoa> map = new HashMap<String, Pessoa>();
   map.put("1", new Pessoa("Mauricio", "111.111.222-33", 23));
   map.put("2", new Pessoa("Geana", "511.411.322-34", 27));
   map.put("3", new Pessoa("Fabricio", "516.416.326-36", 21));
   map.remove("2");

}
}
Link to comment
Share on other sites

boolean found = false;
Iterator<Pessoa> iterator = map.values().iterator();
while (iterator.hasNext() && !found) {
 Pessoa p = iterator.next();
 if (p.getCpf() == "111.222.333-44")
   found = true;
}

if (found)
 System.out.println("Encontrei");
else
 System.out.println("Não encontrei");
Edited by HappyHippyHippo
  • Vote 1
IRC : sim, é algo que ainda existe >> #p@p
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.