1660412040
En Java, vous utilisez un HashMap pour stocker des éléments dans des paires clé/valeur. Vous pouvez accéder aux éléments stockés dans un HashMap
à l'aide de la clé de l'élément, qui est unique pour chaque élément.
Dans cet article, nous parlerons des fonctionnalités d'un HashMap
, de la création d'un HashMap
et des différentes méthodes que nous pouvons utiliser pour interagir avec les données qui y sont stockées.
Avant de travailler avec HashMaps, il est important de comprendre comment ils fonctionnent.
Voici quelques-unes des caractéristiques d'un HashMap
:
Pour créer et utiliser un HashMap, vous devez d'abord importer le java.util.HashMap
package. C'est-à-dire:
import java.util.HashMap;
Voici à quoi ressemble la syntaxe pour créer un nouveau HashMap
:
HashMap<KeyDataType, ValueDataType> HashMapName = new HashMap<>();
Expliquons certains des termes clés de la syntaxe ci-dessus.
KeyDataType
indique le type de données de toutes les clés qui seront stockées dans le fichier HashMap
.ValueDataType
indique le type de données de toutes les valeurs qui seront stockées dans le fichier HashMap
.HashMapName
désigne le nom du HashMap
.Voici un exemple pour simplifier les termes :
HashMap<Integer, String> StudentInfo = new HashMap<>();
Dans le code ci-dessus, nous avons créé un HashMap
appelé StudentInfo
. Les clés qui seront stockées dans HashMap
seront toutes des entiers tandis que les valeurs seront des chaînes.
Vous remarquerez que nous travaillons avec des classes wrapper et non avec des types primitifs lors de la spécification des types de données pour les clés et les valeurs. C'est ainsi que fonctionnent les HashMaps.
Avant de plonger dans les exemples, voici une liste des classes wrapper et leurs types de données primitifs correspondants en Java :
COURS D'EMBALLAGE | TYPES DE DONNÉES PRIMITIFS |
---|---|
Entier | entier |
Personnage | carboniser |
Flotteur | flotteur |
Octet | octet |
Court | court |
Long | long |
Double | double |
booléen | booléen |
Lorsque nous travaillons avec HashMaps, nous utilisons des classes wrapper.
Dans cette section, nous parlerons de certaines des méthodes utiles que vous pouvez utiliser lorsque vous travaillez avec HashMaps.
Vous apprendrez à ajouter, accéder, supprimer et mettre à jour des éléments dans un fichier HashMap
.
HashMap
en JavaPour ajouter des éléments à un HashMap
, nous utilisons la put()
méthode . Il prend en compte deux paramètres - la clé et la valeur de l'élément ajouté.
Voici comment ça fonctionne:
import java.util.HashMap;
class HashMapExample {
public static void main(String[] args) {
HashMap<Integer, String> StudentInfo = new HashMap<>();
StudentInfo.put(1, "Ihechikara");
StudentInfo.put(2, "Jane");
StudentInfo.put(3, "John");
System.out.println(StudentInfo);
// {1=Ihechikara, 2=Jane, 3=John}
}
}
Dans le code ci-dessus, le HashMap
s'appelle StudentInfo
. Nous avons spécifié les clés sous forme d'entiers alors que les valeurs étaient des chaînes : HashMap<Integer, String>
.
Pour ajouter des éléments au HashMap
, nous avons utilisé la put()
méthode :
StudentInfo.put(1, "Ihechikara");
StudentInfo.put(2, "Jane");
StudentInfo.put(3, "John");
Nous avons ajouté trois éléments, chacun ayant un entier comme clé et une chaîne comme valeur.
HashMap
en JavaVous pouvez utiliser la get()
méthode pour accéder aux éléments stockés dans un fichier HashMap
. Il prend un paramètre - la clé de l'élément auquel on accède.
Voici un exemple :
import java.util.HashMap;
class HashMapExample {
public static void main(String[] args) {
HashMap<Integer, String> StudentInfo = new HashMap<>();
StudentInfo.put(1, "Ihechikara");
StudentInfo.put(2, "Jane");
StudentInfo.put(3, "John");
System.out.println(StudentInfo.get(2));
// Jane
}
}
Dans l'exemple ci-dessus, StudentInfo.get(2)
renvoie la valeur avec une clé de 2
. "Jane" a été imprimé sur la console.
Pour modifier la valeur des éléments dans a HashMap
, nous utilisons la replace()
méthode . Il prend deux paramètres - la clé de l'élément à modifier et la nouvelle valeur à lui attribuer.
import java.util.HashMap;
class HashMapExample {
public static void main(String[] args) {
HashMap<Integer, String> StudentInfo = new HashMap<>();
StudentInfo.put(1, "Ihechikara");
StudentInfo.put(2, "Jane");
StudentInfo.put(3, "John");
// Update key 1
StudentInfo.replace(1, "Doe");
System.out.println(StudentInfo);
// {1=Doe, 2=Jane, 3=John}
}
}
Lorsque les éléments ci- HashMap
dessus lui ont été attribués, l'élément avec une clé de 1
avait une valeur de "Ihechikara".
Nous avons changé sa valeur en "Doe" en utilisant la replace()
méthode :StudentInfo.replace(1, "Doe");
HashMap
en JavaVous pouvez utiliser la remove()
méthode pour supprimer un élément d'un fichier HashMap
. Il prend un paramètre - la clé de l'élément à supprimer.
import java.util.HashMap;
class HashMapExample {
public static void main(String[] args) {
HashMap<Integer, String> StudentInfo = new HashMap<>();
StudentInfo.put(1, "Ihechikara");
StudentInfo.put(2, "Jane");
StudentInfo.put(3, "John");
// Remove key 1
StudentInfo.remove(1);
System.out.println(StudentInfo);
// {2=Jane, 3=John}
}
}
En utilisant la remove()
méthode, nous avons supprimé l'élément avec une clé de 1
.
Si vous souhaitez supprimer tous les éléments d'un HashMap
à la fois, vous utilisez la clear()
méthode. C'est-à-dire:
import java.util.HashMap;
class HashMapExample {
public static void main(String[] args) {
HashMap<Integer, String> StudentInfo = new HashMap<>();
StudentInfo.put(1, "Ihechikara");
StudentInfo.put(2, "Jane");
StudentInfo.put(3, "John");
// Remove all items
StudentInfo.clear();
System.out.println(StudentInfo);
// {}
}
}
Il existe d'autres méthodes utiles comme :
containsKey
qui retourne true
si une clé spécifiée existe dans un fichier HashMap
.containsValue
qui retourne true
si une valeur spécifiée existe dans un HashMap
.size()
qui renvoie le nombre d'éléments dans un HashMap
.isEmpty()
qui revient true
si HashMap
a ne contient aucun élément, et ainsi de suite.Dans cet article, nous en avons parlé HashMap
en Java. Tout d'abord, nous avons parlé des fonctionnalités d'un HashMap
.
Nous avons ensuite vu comment créer un HashMap
et certaines des méthodes que vous pouvez utiliser pour interagir avec les données qui y sont stockées, avec des exemples de code.
Bon codage !
Source : https://www.freecodecamp.org/news/what-is-a-java-hashmap/
1600135200
OpenJDk or Open Java Development Kit is a free, open-source framework of the Java Platform, Standard Edition (or Java SE). It contains the virtual machine, the Java Class Library, and the Java compiler. The difference between the Oracle OpenJDK and Oracle JDK is that OpenJDK is a source code reference point for the open-source model. Simultaneously, the Oracle JDK is a continuation or advanced model of the OpenJDK, which is not open source and requires a license to use.
In this article, we will be installing OpenJDK on Centos 8.
#tutorials #alternatives #centos #centos 8 #configuration #dnf #frameworks #java #java development kit #java ee #java environment variables #java framework #java jdk #java jre #java platform #java sdk #java se #jdk #jre #open java development kit #open source #openjdk #openjdk 11 #openjdk 8 #openjdk runtime environment
1624456980
In this tutorial, we’ll take a look at how to sort a HashMap by key in Java.
Let’s go ahead and create a simple HashMap
:
Map<String, Integer> unsortedMap = new HashMap();
unsortedMap.put("John", 21);
unsortedMap.put("Maria", 34);
unsortedMap.put("Mark", 31);
unsortedMap.put("Sydney", 24);
unsortedMap.entrySet().forEach(System.out::println);
We’ve got String
s as keys, and Integer
s as values. Most of the time, you’ll encounter Integer
s or String
s as keys, and custom objects, String
s or Integer
s as values. We’ll want to sort this HashMap
, based on the String
keys.
HashMap
s don’t guarantee to maintain the order of its elements in any case. The order can change through time, and they most definitely won’t be printed back in the order of insertion:
John=21
Mark=31
Maria=34
Sydney=24
If you re-run this program, it’ll keep this order, since HashMap
s order their elements into bins, based on the hash value of the keys. When printing values from a HashMap
, its contents are printed sequentially, so the results will stay the same if we re-run the program multiple times.
#java #how to sort a hashmap by key in java #hashmap #key in java #sort #sort a hashmap by key in java
1620458875
According to some surveys, such as JetBrains’s great survey, Java 8 is currently the most used version of Java, despite being a 2014 release.
What you are reading is one in a series of articles titled ‘Going beyond Java 8,’ inspired by the contents of my book, Java for Aliens. These articles will guide you step-by-step through the most important features introduced to the language, starting from version 9. The aim is to make you aware of how important it is to move forward from Java 8, explaining the enormous advantages that the latest versions of the language offer.
In this article, we will talk about the most important new feature introduced with Java 10. Officially called local variable type inference, this feature is better known as the **introduction of the word **var
. Despite the complicated name, it is actually quite a simple feature to use. However, some observations need to be made before we can see the impact that the introduction of the word var
has on other pre-existing characteristics.
#java #java 11 #java 10 #java 12 #var #java 14 #java 13 #java 15 #verbosity
1624423440
In this tutorial, we’ll take a look at how to sort a HashMap by value in Java.
Let’s go ahead and create a simple HashMap
:
Map<String, Integer> unsortedMap = new HashMap();
unsortedMap.put("John", 21);
unsortedMap.put("Maria", 34);
unsortedMap.put("Mark", 31);
unsortedMap.put("Sydney", 24);
unsortedMap.entrySet().forEach(System.out::println);
We’ve got String
s as keys, and Integer
s as values. And we’d like to sort this map based on the values.
HashMap
s don’t guarantee to maintain the order of its elements in any case. The order can change through time, and they most definitely won’t be printed back in the order of insertion:
John=21
Mark=31
Maria=34
Sydney=24
If you re-run this program, it’ll keep this order, since HashMap
s order their elements into bins, based on the hash value of the keys. When printing values from a HashMap
, its contents are printed sequentially, so the results will stay the same if we re-run the program multiple times.
Note: TreeMap
extends the SortedMap
interface, unlike the HashMap
implementation. TreeMap
s are meant to be the sorted counterpart, however, TreeMap
s only sort by keys, given a comparator.
#java #how to sort a hashmap by value in java #hashmap #value in java #sort
1620462686
On March 16th, 2021, Java 16 was GA. With this new release, tons of new exciting features have been added. Check out the release notes to know more about these changes in detail. This article’s focus will be on Java Records, which got delivered with JEP 395. Records were first introduced in JDK 14 as a preview feature proposed by JEP 359, and with JDK 15, they remained in preview with JEP 384. However, with JDK 16, Records are no longer in preview.
I have picked Records because they are definitely the most favored feature added in Java 16, according to this Twitter poll by Java Champion Mala Gupta.
I also conducted a similar survey, but it was focused on features from Java 8 onwards. The results were not unexpected, as Java 8 is still widely used. Very unfortunate, though, as tons of new features and improvements are added to newer Java versions. But in terms of features, Java 8 was definitely a game-changer from a developer perspective.
So let’s discuss what the fuss is about Java Records.
#java #springboot #java programming #records #java tutorials #java programmer #java records #java 16