【问题标题】:How to check element duplicate in Map java [duplicate]如何在Map java中检查元素重复[重复]
【发布时间】:2018-05-17 17:45:16
【问题描述】:

我有一个函数,允许在 Map 中输入键和值。

这是我的代码

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);
        }
    }
}

我不知道接下来如何检查元素,我将输入。和之前的element一样,如果一样我再输入一次。

【问题讨论】:

  • map.containsKey(sKey);

标签: java collections java-console


【解决方案1】:

在实现 Collection 接口的每个数据结构中都有一个 Collection.contains() 方法!!!!

【讨论】:

  • 但是Map其实并不是一个Collection。
  • 道歉。你可以做 Map.keySet() 然后运行 ​​Collection.contains() 检查!!!!!
【解决方案2】:

添加一个while循环:

  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);
    }
 }

【讨论】:

  • 非常感谢,成功了
猜你喜欢
  • 2013-03-09
  • 2015-07-28
  • 2017-04-14
  • 2016-11-02
  • 2010-09-14
  • 1970-01-01
  • 2023-03-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多