首页 > 解决方案 > 使用HashMap时如何给出条件

问题描述

问题:

编写一个程序来打印给定句子中的所有唯一字符。如果未找到唯一字符,则打印“无唯一字符”。如果找到唯一字符,则打印这些字符,如示例输出中所示。

我的代码:

public class Unique {
    public static void main(String[] args) {
        LinkedHashMap<Character, Integer> list = new LinkedHashMap<Character, Integer>();
        System.out.println("Enter the sentence: ");
        Scanner input = new Scanner(System.in);
        String s = input.nextLine();
        if(!Pattern.matches(".*[a-zA-z]+.*[a-zA-z]",s)) {
            System.out.println("Invalid Sentence");
        } else {
            for(Character c : s.toCharArray()) {
                if (list.containsKey(c)) {
                    list.put(c, list.get(c) + 1);
                } else {
                    list.put(c, 1);
                }
            }
            System.out.println("Unique characters:");
            for(Map.Entry<Character, Integer> e: list.entrySet()) {
                if((int)e.getValue() == 1)   
                   System.out.println(e.getKey());
            }
        }
    }
}

当找不到唯一字符时,我不知道如何为“无唯一字符”提供条件。

标签: java

解决方案


您需要检查地图是否包含任何映射到 1 的值,如果是 - 至少有一个唯一字符。如果相反,则没有唯一字符。使用 lambdas,这可以在一行中完成,例如:

        if (list.values().stream().anyMatch(v -> v == 1)) {
            System.out.println("Unique characters:");
            for (Map.Entry<Character, Integer> e : list.entrySet()) {
                if ((int) e.getValue() == 1)
                    System.out.println(e.getKey());
            }
        } else {
            System.out.println("No unique characters");
        }

请注意 (int) 强制转换不是必需的(根据您的代码),因为取消装箱, e.getValue 已经是一个 int,所以这个:

if ((int) e.getValue() == 1)

可以没有副作用的变成这样:

if (e.getValue() == 1)

如果将 list 变量重命名为 map 以避免混淆,那也很好。


推荐阅读