Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

236
Views
¿Cómo iterar a través de un Mapa en Java?

Necesito iterar a través de un BucketMap y obtener todas las keys , pero ¿cómo llego a algo como buckets[i].next.next.next.key por ejemplo, sin hacerlo manualmente como lo intenté aquí?

 public String[] getAllKeys() { //index of string array "allkeys" int j = 0; String allkeys[] = new String[8]; //iterates through the bucketmap for (int i = 0; i < buckets.length; i++) { //checks wether bucket has a key and value if (buckets[i] != null) { //adds key to allkeys allkeys[j] = buckets[i].key; // counts up the allkeys index after adding key j++; //checks wether next has a key and value if (buckets[i].next != null) { //adds key to allkeys allkeys[j] = buckets[i].next.key; j++; } } } return allkeys; }

Además, ¿cómo puedo inicializar las teclas de String[] allkeys usando la versión de j que obtenemos después de que la iteración se realiza como índice?

about 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Para la utilización básica, el HashMap es el mejor, he explicado cómo iterarlo, más fácil que usar un iterador:

 public static void main (String[] args) { //a map with key type : String, value type : String Map<String,String> mp = new HashMap<String,String>(); mp.put("John","Math"); mp.put("Jack","Math"); map.put("Jeff","History"); //3 differents ways to iterate over the map for (String key : mp.keySet()){ //iterate over keys System.out.println(key+" "+mp.get(key)); } for (String value : mp.values()){ //iterate over values System.out.println(value); } for (Entry<String,String> pair : mp.entrySet()){ //iterate over the pairs System.out.println(pair.getKey()+" "+pair.getValue()); } }

Una explicación rápida:

 for (String name : mp.keySet()){ //Do Something }

significa: "Para todas las cadenas de las claves del mapa, haremos algo, y en cada iteración llamaremos a la clave 'nombre' (puede ser lo que quieras, es una variable)


Aquí vamos :

 public String[] getAllKeys(){ int i = 0; String allkeys[] = new String[buckets.length]; KeyValue val = buckets[i]; //Look at the first one if(val != null) { allkeys[i] = val.key; i++; } //Iterate until there is no next while(val.next != null){ allkeys[i] = val.next.key; val = val.next; i++; } return allkeys; }
about 4 years ago · Santiago Trujillo Report

0

A ver si esto ayuda,

 HashMap< String, String> map = new HashMap<>(); Set<String> keySet = map.keySet(); Iterator<String> iterator = keySet.iterator(); while(iterator.hasNext()) { //iterate over keys } //or iterate over entryset Iterator<Entry<String, String>> iterator2 = map.entrySet().iterator(); while(iterator2.hasNext()) { Entry<String, String> next = iterator2.next(); //get key next.getKey(); //get value next.getValue(); }
about 4 years ago · Santiago Trujillo Report

0

Con Java 8, le sugiero que use Stream API.

Le permitirá iterar a través del Mapa en un enfoque mucho más conveniente:

 public void iterateUsingStreamAPI(Map<String, Integer> map) { map.entrySet().stream() // ... .forEach(e -> System.out.println(e.getKey() + ":" + e.getValue())); }

Busque más ejemplos sobre la iteración a través de mapas en Java .

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!