Java 如何打印阵列中的重复项?

Java 如何打印阵列中的重复项?,java,Java,我已经找到了问题的解决方案,但请随意添加更多或缩短我编写的代码 以下是我已经开发的代码: public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Input Array Length:"); // limit of array int n=sc.nextInt();

我已经找到了问题的解决方案,但请随意添加更多或缩短我编写的代码

以下是我已经开发的代码:

public static void main(String[] args) {     

            Scanner sc = new Scanner(System.in);
            System.out.print("Input Array Length:"); // limit of array

            int n=sc.nextInt();
            System.out.println();


            String  arr[]=new String [n];

            for (int i = 0; i < arr.length; i++) {

                System.out.println("Enter elements:"); // elements of array
                arr[i] = sc.next();
            }



            for (int i = 0; i < arr.length -1; i++) { // start loop

                for (int j = i+1; j < arr.length; j++) 
                {
                    if( (arr[i].equals(arr[j]))) // condition to find duplicate
                    {
                        System.out.println("Duplicate Element is : "+arr[j]);
                    }
                }
            }
        }
publicstaticvoidmain(字符串[]args){
扫描仪sc=新的扫描仪(System.in);
System.out.print(“输入数组长度:”;//数组限制
int n=sc.nextInt();
System.out.println();
字符串arr[]=新字符串[n];
对于(int i=0;i
一种可能的解决方案是创建一个
映射
,其中
是数组中唯一的项,而
-项的计数:

Set<String> duplicates = Arrays.stream(arr)
                               .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())).entrySet().stream()
                               .filter(entry -> entry.getValue() > 1)
                               .map(Map.Entry::getKey)
                               .collect(Collectors.toSet());
Set duplicates=Arrays.stream(arr)
.collect(Collectors.groupingBy(Function.identity(),Collectors.counting()).entrySet().stream()
.filter(条目->条目.getValue()>1)
.map(map.Entry::getKey)
.collect(收集器.toSet());

好吧,如果您正在寻找更可读、更优雅的代码,这段代码可能会有所帮助

String[] myStringArray = { "A", "B", "C", "D", "E" , "A", "B", "A", "AC"};
    List<String> allStr = Arrays.asList( myStringArray );
    Set<String> duplicateStrings = allStr.stream()
            .filter(i -> Collections.frequency(allStr, i) >1)
            .collect(Collectors.toSet());
    System.out.println(duplicateStrings);
String[]myStringArray={“A”、“B”、“C”、“D”、“E”、“A”、“B”、“A”、“AC”};
List allStr=Arrays.asList(myStringArray);
Set duplicateStrings=allStr.stream()
.filter(i->Collections.frequency(allStr,i)>1)
.collect(收集器.toSet());
System.out.println(重复字符串);
解释[始终需要:-)]:

  • 从字符串数组中创建流以进行处理
  • 过滤重复的字符串,以便以后打印
  • 使用
    Collections.frequency()
    获取同一对象的出现次数
  • 如果大于1,则为副本,我们将保留它以便打印(或使用)
  • 最后,将过滤操作的所有输出收集到
    Set
  • 由于集合不允许重复,它将保存重复单词(字符串对象)的单个值
希望能有帮助

接下来我可以看什么


供进一步阅读。

我投票将这个问题作为离题题结束,因为我认为它是一个值得讨论的问题