首页 > 解决方案 > Java:在数组中查找重复项

问题描述

我需要在我的程序中实现重复搜索方法,但出现错误。如果我注释掉重复的搜索部分,程序运行良好。

错误(我注释掉了重复的搜索部分):

  do{ 
   System.out.print("Please enter an integer or -1 to stop: ");
   input=Integer.parseInt(scan.nextLine()); //parse library function 
   /** 
    * for(int i=0; i<A.length; i++){
    *     for(int j=i+1; j<A.length; j++{
    *         if(A[i].equals(A[j]))
    *         System.out.println("Duplicate input. Please enter another 
                          value: ");
    *         }
    *       }
    */
   if(input != -1) //if input is 
   Display.userInput(input);
}
while(input != -1); 

标签: javaarraysduplicates

解决方案


    int A[] = {1, 5, 9, 5, 6};
    if (Arrays.stream(A).boxed()
            .collect(Collectors.groupingBy(Function.identity()))
            .entrySet()
            .stream()
            .map(Map.Entry::getValue)
            .map(Collection::size)
            .anyMatch(s -> s > 1)) {
        System.out.println("Duplicate input. Please enter another value:");
    }

推荐阅读