java - 使用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());
}
}
}
}
当找不到唯一字符时,我不知道如何为“无唯一字符”提供条件。
解决方案
您需要检查地图是否包含任何映射到 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 以避免混淆,那也很好。
推荐阅读
- angularjs - 如果进度条为 100%,AngularJS 删除“活动”类
- python - Python 3 web scraper 非常简单不工作
- python - 如何通过比较另一个数据框中的值来为数据框的列分配值
- delphi - 在delphi中自动增加轨迹栏的过程
- python - Python3:从给定时间播放音频文件
- python - 为什么 day_num 没有定义?
- r - emmeans 无法在 R 中处理类“bigglm”的对象
- python - 无法通过 Facebook Graph API 获取任何事件
- python - 我是给 cross_val_score() 整个数据集还是只给训练集?
- flutter - Flutter StatefulWidget 层次结构