HashMap em Java

Na discussão de hoje, abordaremos o Java HashMap com exemplos , que se destinam a atender às necessidades de aprendizado de nossos alunos

Java HashMap

Você aprendeu no capítulo ArrayList que os arrays contêm itens em uma coleção ordenada que pode ser acessada por números de índice ( ints ).

No que diz respeito aos Java HashMaps , o Hashmap armazena os itens em grupos de pares “ chave/valor ” e você pode acessá-los por um tipo de dados de índice em vez de usar apenas int (por exemplo, String ).

A chave (índice) de um objeto é usada para acessar o valor de outro objeto.

Existem dois tipos de dados que ele pode armazenar: chaves de string e valores de caractere, ou o mesmo tipo, como chaves de string e valores de string.

Crie um objeto HashMap e nomeie-o como sports_players para armazenar chaves de String e valores de String :

import java.util.HashMap; // HashMap class is imported here
HashMap<String, String> sports_players = new HashMap<String, String>();

Crie um objeto HashMap e nomeie-o como rank_Id para armazenar chaves de String e valores de String:

import java.util.HashMap; // HashMap class is imported here
  HashMap<Integer, Integer> rank_Id = new HashMap<Integer, Integer>();


Java HashMap Put()

Existem muitos métodos úteis na classe HashMap . Você pode usar o método put() para adicionar itens a ele, por exemplo:

Declare um objeto HashMap e nomeie-o como sports_players para armazenar chaves de string como nome de esportes e valores de string como nome de jogador famoso.

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import java.util.HashMap; // HashMap class is imported here
public class Main {
public static void main(String[] args) {
HashMap<String, String> sports_players = new HashMap<String, String>(); // The object of Hashmap is created heere in which key and value both are of type String.
sports_players.put("Football","Cristiano Ronaldo");
sports_players.put("Cricket","Sachin Tendulkar");
sports_players.put("Hockey","Wayne Gretzky");
sports_players.put("Baseball","Babe Ruth");
sports_players.put("Rugby","Jonah Lomu");
System.out.println(sports_players);
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Da mesma forma, inicializamos um objeto HashTree que armazena classificação como chaves e Id como valor:

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.util.HashMap; // HashMap class is imported here
public class Main {
public static void main(String[] args) {
HashMap<Integer, Integer> rank_Id = new HashMap<Integer, Integer>();// Here, a HashMap object is created and named as rank_Id, whose key and value are both integers.
rank_Id.put(1,10001);
rank_Id.put(2,10002);
rank_Id.put(3,10003);
rank_Id.put(4,10004);
rank_Id.put(5,10005);
System.out.println(rank_Id);
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

 


Java HashMap Get()

Quando discutimos Java HashMap , o método get() e a chave são usados ​​para acessar valores em um HashMap.

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import java.util.HashMap; // HashMap class is imported here
public class Main {
public static void main(String[] args) {
HashMap<String, String> it_Firms = new HashMap<String,String >();
it_Firms.put("1","Cognizant");
it_Firms.put("2","Vates-Software");
it_Firms.put("3","MantorMate");
it_Firms.put("4","Resultant");
it_Firms.put("5","Fortegrp");
// All Elements of HashMap
System.out.println(it_Firms);
// By accessing the value at key number 3
System.out.println("\nValue at key 3: "+it_Firms.get("3"));
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Outra Abordagem:

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import java.util.HashMap; // HashMap class is imported here
public class Main {
public static void main(String[] args) {
HashMap<Integer,Integer> rank_Age = new HashMap<Integer,Integer>();
rank_Age.put(1,21);
rank_Age.put(2,25);
rank_Age.put(3,31);
rank_Age.put(4,41);
rank_Age.put(5,37);
// All Elements of HashMap
System.out.println(rank_Age);
// By accessing the Age at key number 2
System.out.println("\nValue at key 2: "+rank_Age.get(2));
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

 


Java HashMap Remove()

Usando o método remove() , remova um item referenciando sua chave.

O exemplo abaixo mostra a remoção de Key (“ Team 4 ”) avaliado como Cleveland Cavaliers.

Hashmap remove Example: 1 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import java.util.HashMap; // HashMap class is imported here
public class Main {
public static void main(String[] args) {
HashMap<String,String> nba_Teams = new HashMap<String,String>();
nba_Teams.put("Team 1"," Boston Celtics");
nba_Teams.put("Team 2"," Chicago Bulls");
nba_Teams.put("Team 3"," Atlanta Hawks");
nba_Teams.put("Team 4"," Cleveland Cavaliers");
nba_Teams.put("Team 5"," Detroit Pistons");
// Here we print all Elements of the HashMap Object named as nba_Teams before removing an item
System.out.println("\nBefore Removing Value: "+nba_Teams);
// Removing Cleveland Cavaliers by using its key (Team 4)
String removed= nba_Teams.remove("Team 4");
System.out.println("\nRemoved Value is: "+removed);
// Printing all elements of HashMap after an element was removed:
System.out.println("\nAfter Removing value: "+nba_Teams);
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Example: 2 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import java.util.HashMap; // HashMap class is imported here
public class Main {
public static void main(String[] args) {
HashMap<Float,Float> person_Id_Height = new HashMap<Float,Float>();
person_Id_Height.put(10f,5.4f);
person_Id_Height.put(20f,5.6f);
person_Id_Height.put(30f,5.7f);
person_Id_Height.put(40f,6.2f);
person_Id_Height.put(50f,5.11f);
// Here we print all Elements of the HashMap Object named as person_Id_Height before the item is element
System.out.println("\nBefore Removing Value: "+person_Id_Height);
// Removing from person_Id_Height HashMap by using its key (40f)
float removed= person_Id_Height.remove(40f);
System.out.println("\nRemoved Value is: "+removed);
// Printing all elements of HashMap after an element was removed:
System.out.println("\nAfter Removing value: "+person_Id_Height);
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

 

Usando o método clear() , você pode remover todos os itens do objeto HashMap:

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import java.util.HashMap; // HashMap class is imported here
public class Main {
public static void main(String[] args) {
HashMap<String,String> product_code = new HashMap<String,String>();
product_code.put("Cookies","102313");
product_code.put("Biscuits","153532");
product_code.put("Snacks","632123");
product_code.put("PopCorns","361232");
product_code.put("Chocolates","734231");
// Here we print all Elements of the HashMap Object named as product_code
System.out.println("HashMap: "+product_code);
// After using .clear() method our HashMap becomes empty
product_code.clear();
// Printing all elements of HashMap after all elements were removed:
System.out.println("After clearing the HashMap we get: "+product_code);
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Aqui limpamos todo o HashMap usando o método clear() :

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import java.util.HashMap; // HashMap class is imported here
public class Main {
public static void main(String[] args) {
HashMap<Float,Float> results_division_ = new HashMap<Float,Float>();
results_division_.put(14f/5f,2.8f);
results_division_.put(18f/7f,2.57f);
results_division_.put(19f/4f,4.75f);
results_division_.put(11f/3f,3.66f);
// Here we print all Elements of the HashMap Object named as results_division_
System.out.println("HashMap: "+results_division_);
// After using .clear() method our HashMap becomes empty
results_division_.clear();
// Printing all elements of HashMap after all elements were removed:
System.out.println("After clearing the HashMap we get: "+results_division_);
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Tamanho do HashMap

O método size() pode ser usado para descobrir quantos itens existem no HashMap:

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import java.util.HashMap; // HashMap class is imported here
public class Main {
public static void main(String[] args) {
HashMap<String,String> rank_billionaires_name = new HashMap<String,String>();
rank_billionaires_name.put("Rank 1: "," Bernard Arnault & family");
rank_billionaires_name.put("Rank 2: "," Elon Musk");
rank_billionaires_name.put("Rank 3: "," Gautam Adani");
rank_billionaires_name.put("Rank 4: "," Jeff Bezos");
// Here we print all Elements of the HashMap Object named as rank_billionaires_name
System.out.println("HashMap: "+rank_billionaires_name);
// By using size() method we can determine the size of our HashMap
System.out.println("\nSize of HashMap: "+rank_billionaires_name.size());
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import java.util.HashMap; // HashMap class is imported here
public class Main {
public static void main(String[] args) {
HashMap<Character,Character> vowels_List = new HashMap<Character,Character>();
vowels_List.put('a','A');
vowels_List.put('e','E');
vowels_List.put('i','I');
vowels_List.put('o','O');
vowels_List.put('u','U');
// Here we print all Elements of the HashMap Object named as vowels_List
System.out.println("Vowels HashMap: "+vowels_List);
// By using size() method we can determine the size of our HashMap
System.out.println("\nSize of HashMap: "+vowels_List.size());
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Percorrer um HashMap

Um loop for-each percorre os itens de um HashMap.

Lembre-se: Se você quiser apenas as chaves, use o método keySet() e, se quiser apenas os valores, use o método values() .

Os exemplos a seguir mostram como podemos imprimir todas as chaves do HashMap usando o método keySet() :

Example: 1 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import java.util.HashMap; // HashMap class is imported here
public class Main {
public static void main(String[] args) {
HashMap<String, String> it_Firms = new HashMap<String,String >();
it_Firms.put("1","Cognizant");
it_Firms.put("2","Vates-Software");
it_Firms.put("3","MantorMate");
it_Firms.put("4","Resultant");
it_Firms.put("5","Fortegrp");
// Using for-each loop to traverse through the keys of HashMap object named it_Firms
for(String mrx:it_Firms.keySet()){
System.out.println(mrx);
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Example:2 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import java.util.HashMap; // HashMap class is imported here
public class Main {
public static void main(String[] args) {
HashMap<Integer,Integer> odd_Even = new HashMap<Integer,Integer>();
odd_Even.put(1,2);
odd_Even.put(3,4);
odd_Even.put(5,6);
odd_Even.put(7,8);
odd_Even.put(9,10);
// Using for-each loop to print through the keys of HashMap object named odd_Even
for(Integer ample:odd_Even.keySet()){
System.out.println(ample);
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Da mesma forma, também podemos percorrer e imprimir os valores do HashMap usando o método values() :

Example:3 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import java.util.HashMap; // HashMap class is imported here
public class Main {
public static void main(String[] args) {
HashMap<String, String> it_Firms = new HashMap<String,String >();
it_Firms.put("1","Cognizant");
it_Firms.put("2","Vates-Software");
it_Firms.put("3","MantorMate");
it_Firms.put("4","Resultant");
it_Firms.put("5","Fortegrp");
// Using for-each loop to print the values of HashMap object named it_Firms using the values() method
for(String ample:it_Firms.values()){
System.out.println(ample);
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Imprimimos as chaves e valores do objeto nomeado como odd_Even do HashMap:

Example:4 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import java.util.HashMap; // HashMap class is imported here
public class Main {
public static void main(String[] args) {
HashMap<Integer,Integer> odd_Even = new HashMap<Integer,Integer>();
odd_Even.put(1,2);
odd_Even.put(3,4);
odd_Even.put(5,6);
odd_Even.put(7,8);
odd_Even.put(9,10);
// Using for-each loop to print all the values of HashMap object named odd_Even using the values() method
for(Integer ample:odd_Even.values()){
System.out.println(ample);
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Da mesma forma, também podemos imprimir ambos ( Chaves e valores ) de uma vez usando o método keySet() e o método get() :

Example:5 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import java.util.HashMap; // HashMap class is imported here
public class Main {
public static void main(String[] args) {
HashMap<String, String> it_Firms = new HashMap<String,String >();
it_Firms.put("1","Cognizant");
it_Firms.put("2","Vates-Software");
it_Firms.put("3","MantorMate");
it_Firms.put("4","Resultant");
it_Firms.put("5","Fortegrp");
// We can also access the keys and values at a time
for(String ample:it_Firms.keySet()){
System.out.println("Key: "+ample+" Value: "+it_Firms.get(ample));
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Example:6 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import java.util.HashMap; // HashMap class is imported here
public class Main {
public static void main(String[] args) {
HashMap<Integer,Integer> odd_Even = new HashMap<Integer,Integer>();
odd_Even.put(1,2);
odd_Even.put(3,4);
odd_Even.put(5,6);
odd_Even.put(7,8);
odd_Even.put(9,10);
// As we did in the example above, we can print the keys and the values at a same time using th for-each loop
for(Integer mrx:odd_Even.keySet()){
System.out.println("Key Number: "+mrx+" Value: "+odd_Even.get(mrx));
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

 


Outros tipos

Na verdade, existem objetos que compõem as chaves e os valores de um HashMap. Objetos do tipo “ String ” e “Integer” foram usados ​​nos exemplos acima. Strings são objetos em Java (não tipos primitivos).

Se quiser acessar outros tipos , como int , você precisará especificar uma classe wrapper equivalente: Integer.

Quando se trata de outros tipos primitivos , use Boolean para boolean, caractere para caractere, double para double, etc.

Para armazenar chaves Integer e valores String , criamos um objeto HashMap chamado silent_letter_words:

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
HashMap <Integer,String> silent_letter_words=new HashMap<Integer,String>();
silent_letter_words.put(1,"Bomb");
silent_letter_words.put(2,"Knife");
silent_letter_words.put(3,"Kitchen");
silent_letter_words.put(4,"Wrap");
silent_letter_words.put(5,"Cupboard");
for(int mrx:silent_letter_words.keySet()){
System.out.println("Number "+mrx+" ="+" Word: "+silent_letter_words.get(mrx));
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Além disso, também podemos imprimir o nome das pessoas como chaves e seus pesos corporais como valor , conforme mostrado abaixo:

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
HashMap <String,Double> person_Weight=new HashMap<String,Double>();
person_Weight.put("Joseph",56.8d);
person_Weight.put("Diana",64.2d);
person_Weight.put("Emma",44.1d);
person_Weight.put("Sophia",77.4d);
person_Weight.put("Noah",58.9d);
for(String ample:person_Weight.keySet()){
System.out.println(ample+" have "+"Weight= "+person_Weight.get(ample)+" kgs");
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

 

Nós valorizamos o seu feedback.
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0

Assine a nossa newsletter
Digite seu e-mail para receber um resumo semanal de nossos melhores posts. Saber mais!
ícone