首页 > 解决方案 > Java检查数组元素重复是否存在而不使用循环?

问题描述

我做了一个对字检测器,它给了我一个trueor的输出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;                                       
    }                                       
}

标签: javaloopscollections

解决方案


这是您的原因的简单示例

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

推荐阅读