Léon  Peltier

Léon Peltier

1660412040

Comment Créer Un HashMap En Java

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 HashMapet des différentes méthodes que nous pouvons utiliser pour interagir avec les données qui y sont stockées.

Quelles sont les fonctionnalités d'un HashMap en Java ?

Avant de travailler avec HashMaps, il est important de comprendre comment ils fonctionnent.

Voici quelques-unes des caractéristiques d'un HashMap:

  • Les éléments sont stockés dans des paires clé/valeur.
  • Les articles ne conservent aucun ordre lorsqu'ils sont ajoutés. Les données ne sont pas ordonnées.
  • Dans le cas où il y a des clés en double, la dernière écrasera les autres.
  • Les types de données sont spécifiés à l'aide de classes wrapper au lieu de types de données primitifs.

Comment créer un HashMap en Java

Pour créer et utiliser un HashMap, vous devez d'abord importer le java.util.HashMappackage. 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.

  • KeyDataTypeindique le type de données de toutes les clés qui seront stockées dans le fichier HashMap.
  • ValueDataTypeindique le type de données de toutes les valeurs qui seront stockées dans le fichier HashMap.
  • HashMapNamedé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 HashMapappelé StudentInfo. Les clés qui seront stockées dans HashMapseront 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 :

Classes wrapper et types primitifs en Java

COURS D'EMBALLAGETYPES DE DONNÉES PRIMITIFS
Entierentier
Personnagecarboniser
Flotteurflotteur
Octetoctet
Courtcourt
Longlong
Doubledouble
booléenbooléen

Lorsque nous travaillons avec HashMaps, nous utilisons des classes wrapper.

Méthodes HashMap en Java

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.

Comment ajouter des éléments à un HashMapen Java

Pour 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 HashMaps'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.

Comment accéder aux éléments dans un HashMapen Java

Vous 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.

Comment modifier la valeur des éléments dans un HashMap en Java

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- HashMapdessus lui ont été attribués, l'élément avec une clé de 1avait une valeur de "Ihechikara".

Nous avons changé sa valeur en "Doe" en utilisant la replace()méthode :StudentInfo.replace(1, "Doe");

Comment supprimer des éléments dans un HashMapen Java

Vous 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 :

  • containsKeyqui retourne truesi une clé spécifiée existe dans un fichier HashMap.
  • containsValuequi retourne truesi une valeur spécifiée existe dans un HashMap.
  • size()qui renvoie le nombre d'éléments dans un HashMap.
  • isEmpty()qui revient truesi HashMapa ne contient aucun élément, et ainsi de suite.

Sommaire

Dans cet article, nous en avons parlé HashMapen Java. Tout d'abord, nous avons parlé des fonctionnalités d'un HashMap.

Nous avons ensuite vu comment créer un HashMapet 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/

#java 

What is GEEK

Buddha Community

Comment Créer Un HashMap En Java
Tyrique  Littel

Tyrique Littel

1600135200

How to Install OpenJDK 11 on CentOS 8

What is OpenJDK?

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

How to Sort a HashMap by Key in Java

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 Strings as keys, and Integers as values. Most of the time, you’ll encounter Integers or Strings as keys, and custom objects, Strings or Integers as values. We’ll want to sort this HashMap, based on the String keys.

HashMapdon’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 HashMaps 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

Samanta  Moore

Samanta Moore

1620458875

Going Beyond Java 8: Local Variable Type Inference (var) - DZone Java

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

Joseph  Murray

Joseph Murray

1624423440

How to Sort a HashMap by Value in Java

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 Strings as keys, and Integers as values. And we’d like to sort this map based on the values.

HashMapdon’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 HashMaps 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. TreeMaps are meant to be the sorted counterpart, however, TreeMaponly sort by keys, given a comparator.

#java #how to sort a hashmap by value in java #hashmap #value in java #sort

Samanta  Moore

Samanta Moore

1620462686

Spring Boot and Java 16 Records

In this article, we will discuss Java 16’s newest feature, Records. Then we will apply this knowledge and use it in conjunction with a Spring Boot application.

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