HashSet em Java

Há uma discussão sobre o Java Hashset para atender melhor às necessidades dos alunos.

Java HashSet

Quando se trata de Java HashSet , um HashSet consiste em itens que são todos exclusivos e faz parte do pacote java.util.

Um objeto HashSet será criado para armazenar strings e será nomeado como Programming_language:

import java.util.HashSet; // Here we have imported the class named as HashSet from java.util package

public class Main {
    public static void main(String[] args) {

        HashSet programming_languages=new HashSet();
    }
}

Da mesma forma, aqui criamos outro objeto HashSet e o nomeamos como “NFL_teams”:

import java.util.HashSet; // Here we have imported the class named as HashSet from java.util package

public class Main {
    public static void main(String[] args) {

        HashSet nfl_Teams=new HashSet();
    }
}




Java HashSet Add()

Muitos métodos úteis estão disponíveis na classe HashSet . Por exemplo, add() permite adicionar itens:

Utilizamos o método add() para inserir elementos no objeto HashSet nomeado como Programming_languages ​​conforme o exemplo abaixo:

Java HashSet Add() Example:1 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import java.util.HashSet; // Here we have imported the class named as HashSet from java.util package
public class Main {
public static void main(String[] args) {
HashSet programming_languages=new HashSet();
programming_languages.add("Java");
programming_languages.add("Python");
programming_languages.add("C language");
programming_languages.add("C# programming language");
programming_languages.add("Java");
System.out.println(programming_languages);
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Java HashSet Adicionar exemplos

Da mesma forma, o exemplo fornecido também adiciona nomes das equipes nfl ao objeto HashSet denominado nfl_Teams usando o método add().

Java HashSet Add() Example:2 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import java.util.HashSet; // Here we have imported the class named as HashSet from java.util package
public class Main {
public static void main(String[] args) {
HashSet nfl_Teams=new HashSet();
nfl_Teams.add("Arizona Cardinals");
nfl_Teams.add("Atlanta Falcons");
nfl_Teams.add("Cincinnati Bengals");
nfl_Teams.add("Baltimore Ravens");
nfl_Teams.add("Atlanta Falcons");
System.out.println(nfl_Teams);
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Lembrete: Nos exemplos acima, mesmo que “ Java ” apareça duas vezes no primeiro exemplo e “Atlanta Falcons” seja repetido novamente no segundo, eles aparecem apenas uma vez em cada conjunto, pois de acordo com a propriedade de HashSet cada conjunto deve conter todos todos os elementos únicos.


Java HashSet Contém()

É possível verificar a existência de um item em um HashSet usando o método contains() .

Utilizando o método container() podemos determinar se a string faz parte do HashSet ou não , conforme o exemplo 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
import java.util.HashSet; // HashSet class is imported here
public class Main {
public static void main(String[] args) {
HashSet sports_players = new HashSet(); // The object of HashSet is created here.
sports_players.add("Cristiano Ronaldo");
sports_players.add("Sachin Tendulkar");
sports_players.add("Wayne Gretzky");
sports_players.add("Babe Ruth");
sports_players.add("Jonah Lomu");
System.out.println(sports_players.contains("Sachin Tendulkar")); // Result as true as string Sachin Tendulkar is a part of the HashSet
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Agora colocando o valor da string em “Virat Kohli” para verificar se existe no HashSet ou não:

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.HashSet; // HashSet class is imported here
public class Main {
public static void main(String[] args) {
HashSet sports_players = new HashSet(); // The object of HashSet is created here.
sports_players.add("Cristiano Ronaldo");
sports_players.add("Sachin Tendulkar");
sports_players.add("Wayne Gretzky");
sports_players.add("Babe Ruth");
sports_players.add("Jonah Lomu");
System.out.println(sports_players.contains("Virat Kohli")); // Shows output as false, as string Virat Kohli is not a part of the given HashSet
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

 


Java HashSet Remove() e Clear()

Assim como com Java HashMap e ArrayList , você pode excluir um item usando o método remove() :

O exemplo dado mostra a remoção do número 2 do objeto HashSet chamado “numbers”:

HashSet 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
import java.util.HashSet; // HashSet class is imported here
public class Main {
public static void main(String[] args) {
HashSet numbers = new HashSet(); // The object of HashSet is created here and its datatype is Integer.
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
numbers.add(5);
numbers.remove(2); // Number 2 is removed from the HashSet
System.out.println(numbers);
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

HashSet Remove() 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
import java.util.HashSet; // HashSet class is imported here
public class Main {
public static void main(String[] args) {
HashSet heights_record = new HashSet(); // The object of HashSet is created here having the datatype float.
heights_record.add(5.6f);
heights_record.add(6.1f);
heights_record.add(5.3f);
heights_record.add(6.11f);
heights_record.add(5.2f);
heights_record.remove(6.11f); // the height 6.11 is removed from the HashSet
System.out.println(heights_record);
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Para esvaziar o HashSet, use o método clear() :

HashSet clear() 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
import java.util.HashSet; // Here we have imported the class named as HashSet from java.util package
public class Main {
public static void main(String[] args) {
HashSet mlb_Teams=new HashSet();
mlb_Teams.add("Miami Marlins");
mlb_Teams.add("Atlanta Braves");
mlb_Teams.add("NewYork Mets");
mlb_Teams.add("Philadelphia Phillies");
mlb_Teams.add("Washington Nationals");
System.out.println("\nBefore using the clear method: "+mlb_Teams);
mlb_Teams.clear(); // Clear method is used here which makes the HashSet empty
System.out.println("\nAfter using the clear method: "+mlb_Teams);
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

HashSet clear() 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
import java.util.HashSet; // Here we have imported the class named as HashSet from java.util package
public class Main {
public static void main(String[] args) {
HashSet sports_Cars=new HashSet();
sports_Cars.add("Mazda MX-5 Miata");
sports_Cars.add("Subaru BRZ");
sports_Cars.add("Toyota GR86");
sports_Cars.add("Supra");
sports_Cars.add("Chevy Camaro ZL1");
System.out.println("\nBefore using the clear method: "+sports_Cars);
sports_Cars.clear(); // Clear method is used here which makes the HashSet empty
System.out.println("\nAfter using the clear method: "+sports_Cars);
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

 


Java HashSet Size()

Use o método size() para determinar o número de elementos no HashSet:

O exemplo a seguir calcula o número de elementos do HashSet nomeado como nba_Teams usando o método size() :

HashSet Size() 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
import java.util.HashSet; // Here we have imported the class named as HashSet from java.util package
public class Main {
public static void main(String[] args) {
HashSet nba_Teams=new HashSet();
nba_Teams.add("Boston Celtics");
nba_Teams.add("Chicago Bulls");
nba_Teams.add("Atlanta Hawks ");
nba_Teams.add("Brooklyn Nets");
nba_Teams.add("Cleveland Cavaliers");
System.out.println("The HashSet contains "+nba_Teams.size()+" elements");
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

HashSet Size() 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
import java.util.HashSet; // Here we have imported the class named as HashSet from java.util package
public class Main {
public static void main(String[] args) {
HashSet laptop_brands= new HashSet();
laptop_brands.add("Dell");
laptop_brands.add("Hp");
laptop_brands.add("Samsung");
laptop_brands.add("Asus");
laptop_brands.add("Acer");
System.out.println("The size of the given HashSet is: "+laptop_brands.size());
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Percorrer o HashSet

Usando um loop for-each, podemos percorrer os itens de um HashSet .

Aqui usamos um loop for-each para imprimir todos os elementos do HashSet nomeados como “alfabetos”:

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
import java.util.HashSet; // Here we have imported the class named as HashSet from java.util package
public class Main {
public static void main(String[] args) {
HashSet alphabets=new HashSet();
alphabets.add('A');
alphabets.add('B');
alphabets.add('C');
alphabets.add('D');
alphabets.add('E');
System.out.println("Using the for-each loop to print elements of the HashSet named alphabets: ");
for (char mrx:alphabets) {
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.HashSet; // Here we have imported the class named as HashSet from java.util package
public class Main {
public static void main(String[] args) {
HashSet billionaires =new HashSet();
billionaires.add("Bernard Arnault");
billionaires.add("Elon Musk");
billionaires.add("Gautam Adani");
billionaires.add("Bill Gates");
billionaires.add("Jeff Bezos");
for(String ample :billionaires ) {
System.out.println(ample);
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Outros tipos

HashSets são, na verdade, coleções de objetos. Com base nos exemplos acima, construímos elementos (objetos) dos tipos “String” “int” “float” e “char”.

Você deve se lembrar que em Java, o tipo String é um objeto (não um tipo primitivo). É necessário especificar uma classe wrapper equivalente para outros tipos, como int , char , float , boolean e double, que é Integer , Character , Float, Boolean e Double.

Se você deseja armazenar valores duplos em um HashSet, siga o exemplo 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.HashSet; // Here we have imported the class named as HashSet from java.util package
public class Main {
public static void main(String[] args) {
HashSet double_numbers =new HashSet(); // Here we use double data type and utilized the wrapper class Double
double_numbers.add(1412.541231d);
double_numbers.add(2312.41412d);
double_numbers.add(5345.234234d);
double_numbers.add(623.6345324d);
double_numbers.add(854.6524423d);
for(double mrx :double_numbers ) {
System.out.println("Value : "+mrx);
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Da mesma forma, podemos usar o tipo de dados boolean referindo-se à sua classe wrapper Boolean para criar o seguinte HashSet:

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
import java.util.HashSet; // Here we have imported the class named as HashSet from java.util package
public class Main {
public static void main(String[] args) {
HashSet boolean_Values =new HashSet(); // Here we use boolean data type and utilized the wrapper class Boolean
boolean_Values.add(false);
boolean_Values.add(true);
boolean_Values.add(false);
boolean_Values.add(true);
boolean_Values.add(false);
boolean_Values.add(false);
boolean_Values.add(false);
for (boolean mr_x:boolean_Values) {
System.out.println(mr_x); // Only different values are printed even there are repeated values in this code which satisfies the property of the HashSet to show unique elements only
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Aqui estão alguns pontos-chave sobre o Java HashSet:

  1. Um elemento em um HashSet é armazenado por hash.
  2. Existem apenas elementos únicos em um HashSet.
  3. Valores nulos são permitidos em HashSets.
  4. A classe HashSet não está sincronizada.
  5. A ordem de inserção não é mantida pelo HashSet.
  6. Os elementos são inseridos com base em seus hashcodes.
  7. As operações de pesquisa são melhor executadas usando HashSets.
  8. A capacidade padrão do HashSet é 16 e seu fator de carga é 0,75.
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