java - Java检查数组元素重复是否存在而不使用循环?
问题描述
我做了一个对字检测器,它给了我一个true
or的输出false
。
如果字符串数组中的值包含相同的字符串字母(重复)将返回true
.
我使用嵌套循环使用下面的代码
现在,我想在不使用任何循环的情况下执行相同的概念?
我该怎么做,有什么例子或java collection framework
需要什么类型的?
谢谢
主要的:
public class Main
{
public static void main(String[] args)
{
String[] box = {"Monkey","Lion","Elephant","Zebra","Tiger", "Hippo"};
String[] box2 = {"Shop","Biscuit","Cake","Cake"};
String[] box3 = {"Entrance","Gate","Price","Door","Gate"};
String[] box4 = {"Female","Male"};
System.out.println(Pairfinder.test(box)); //false
System.out.println(Pairfinder.test(box2)); //true
System.out.println(Pairfinder.test(box3)); //true
System.out.println(Pairfinder.test(box4)); //false
}
}
子:
public class Pairfinder
{
public static boolean test(String[] value)
{
for (int i = 0; i < value.length; i++) {
for (int j = 0; j < value.length; j++) {
if (value[i].equals(value[j]) && i != j) {
return true;
}
}
}
return false;
}
}
解决方案
这是您的原因的简单示例
public static void main(String[] args) {
String[] box = {"Monkey", "Lion", "Elephant", "Zebra", "Tiger", "Hippo"};
String[] box2 = {"Shop", "Biscuit", "Cake", "Cake"};
String[] box3 = {"Entrance", "Gate", "Price", "Door", "Gate"};
String[] box4 = {"Female", "Male"};
System.out.println(checkIt(box)); //false
System.out.println(checkIt(box2)); //true
System.out.println(checkIt(box3)); //true
System.out.println(checkIt(box4)); //false
}
public static boolean checkIt(String[] text) {
return !Arrays.stream(text).allMatch(new HashSet<>()::add);
}
推荐阅读
- linux - 特定于应用程序的 linux 系统调优
- c++ - 我的程序中出现 segsigv 错误的原因是什么?
- python - 如何解决在 Kivy 中没有属性“文本”的 NoneType 对象?
- python-3.x - Windows 注册表 DWORD 修改
- coq - 转换正式语言的声明
- java - java.lang.String 类型的值失败无法转换为 JSONObject
- linq - .Include 是否仍在 Entity Framework Core 和 .NET 5.0 上工作?
- ios - 在 Swift 中,如何访问与自定义单元格中的图像交互的行的 indexPath
- javascript - 添加删除 tr td 行而不单击打开 4 字段并单击后一一打开?
- c++ - 如何比较两个相等但一个按升序排列而另一个按降序排列的数组?