【问题标题】:How to fix the duplicate word of arraylist in hashmap?如何修复hashmap中arraylist的重复词?
【发布时间】:2019-11-09 20:02:27
【问题描述】:

制作一个可以根据首字母对单词进行排序的程序。从一个正常的循环直到退出应用程序开始。您的数据将存储在“字符串到字符串列表的映射”中。每次用户输入一个单词时,查看第一个字母并将其添加到正确的列表中。他们退出后,打印出每个字母的所有单词。

public static void main(String[] args) {

    Map<String, ArrayList<String>> MyMap = new HashMap<String, ArrayList<String>>();
    ArrayList<String> MyList = new ArrayList<String>();

    Scanner scanner = new Scanner(System.in);

    int input;
    String MyString = null;

    while (true) {
        System.out.println("Press (1) to enter a word. n/Press (2) to exit.");
        while (!scanner.hasNextInt()) {
            scanner.next();
            System.out.println("Need to press number (1) or (2)");
        }
        input = scanner.nextInt();
        if (input == 1) {
            System.out.println("Enter a word:");
            MyString = scanner.next();
        }
        if (MyMap.containsKey(MyString.substring(0, 1))) {
            MyMap.get(MyString.substring(0, 1)).add(MyString);
        }
        if (!MyMap.containsKey(MyString.substring(0, 1))) {
            MyList = new ArrayList<String>();
            MyList.add(MyString);
            MyMap.put(MyString.substring(0, 1), MyList);
        }
        if (input == 2) {
            MyMap.entrySet().forEach(entry -> {
                System.out.println(entry.getKey() + " " + entry.getValue());
            });
            break;
        }
    }

    scanner.close();

}

我的输出将打印出我输入的最后一个单词的副本。

例如:

输入一个单词: 啊 抗体 巴 公元前 按 (1) 输入单词。按 (2) 退出。 2 一个 [aa, ab] b [ba, bc, bc]

【问题讨论】:

    标签: java arrays hashmap


    【解决方案1】:

    在为MyString 分配新值之前,您只测试input 是否为1,但当input 不是1(例如2)时,您将继续使用之前的值(例如@987654327 @第二次)。改变

    if (input == 1) {
        System.out.println("Enter a word:");
        MyString = scanner.next();
    }
    

    添加else;喜欢

    if (input == 1) {
        System.out.println("Enter a word:");
        MyString = scanner.next();
    } else {
        continue;
    }
    

    此外,您应该遵循 Java 命名约定。 MyString 看起来像一个类名。您可以将以下逻辑向上移动,而不是 else; (我对其进行了一些重构)。喜欢,

    if (input == 1) {
        String s = MyString.substring(0, 1);
        if (!MyMap.containsKey(s)) {
            MyMap.put(s, new ArrayList<>());
        }
        MyMap.get(s).add(MyString);
    }
    

    【讨论】:

      【解决方案2】:

      您可以更改地图类型以满足您的需求:

      Map<String, LinkedHashSet<String>>
      

      重复的值不会插入到集合中,您将保持插入顺序。

      Map<Character, LinkedHashSet<String>> 
      

      似乎更准确,因为您只需要键值中的字符。

      【讨论】:

        猜你喜欢
        • 2018-04-12
        • 1970-01-01
        • 1970-01-01
        • 2011-12-09
        • 2016-01-13
        • 2015-04-18
        • 1970-01-01
        • 1970-01-01
        • 2018-02-25
        相关资源
        最近更新 更多