javacollectionsjava-console

How to check element duplicate in Map java


I have a function, which allow input key and value into Map.

here my code

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class MapDemo {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        Map<String, Integer> map = new HashMap<>();
        System.out.println("Elemment number: ");
        String sNum = input.nextLine();
        int iNum = Integer.parseInt(sNum);
        for (int i = 0; i < iNum; i++) {
            System.out.println("Key: ");
            String sKey = input.nextLine();
            System.out.println("Value: ");
            String sValue = input.nextLine();
            int iValue = Integer.parseInt(sValue);
            map.put(sKey, iValue);
        }
    }
}

I don't know how to check element next, which I will input. it the same with element before, and if it same I will input again.


Solution

  • Add a while loop :

      public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        Map<String, Integer> map = new HashMap<>();
        System.out.println("Elemment number: ");
        String sNum = input.nextLine();
        int iNum = Integer.parseInt(sNum);
        for (int i = 0; i < iNum; i++) {
            String sKey ;
            do {
                System.out.println("Key: ");
                sKey = input.nextLine();
            } while (map.containsKey(sKey));
    
            System.out.println("Value: ");
            String sValue = input.nextLine();
            int iValue = Integer.parseInt(sValue);
            map.put(sKey, iValue);
        }
     }