如何移除 Java 数组中重复的元素?


要检测数组中的重复值,需要将数组的每个元素与其余所有元素比较,如果匹配的话,则得到重复元素。

一种解决方案是使用两个循环(嵌套),其中内循环从 i+1 开始(其中 i 是外循环的变量)以避免重复。

Apache Commons 提供了一个名为 org.apache.commons.lang3 的库,以下是向项目添加库的 Maven 依赖项。

<dependencies>
   <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-lang3</artifactId>
      <version>3.0</version>
   </dependency>
</dependencies>

此软件包提供了一个名为 ArrayUtils 的类,使用此类的 remove() 方法可以删除给定数组中检测到的重复元素。

示例

import java.util.Arrays;
import java.util.Scanner;
import org.apache.commons.lang3.ArrayUtils;
public class DeleteDuplicate {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the size of the array that is to be created::");
      int size = sc.nextInt();
      int[] myArray = new int[size];
      System.out.println("Enter the elements of the array ::");
      for(int i=0; i<size; i++) {
         myArray[i] = sc.nextInt();
      }
      System.out.println("The array created is ::"+Arrays.toString(myArray));
      for(int i=0; i<myArray.length-1; i++) {
         for (int j=i+1; j<myArray.length; j++) {
            if(myArray[i] == myArray[j]) {
               myArray = ArrayUtils.remove(myArray, j);
            }
         }
      }
      System.out.println("Array after removing elements ::"+Arrays.toString(myArray));
   }
}

输出

Enter the size of the array that is to be created ::
6
Enter the elements of the array ::
232
232
65
47
89
42
The array created is :: [232, 232, 65, 47, 89, 42]
Array after removing elements :: [232, 65, 47, 89, 42]

更新于: 30-Jul-2019

3K+ 次浏览

启动你的 职业生涯

完成课程即可获得认证

开始学习
广告
© . All rights reserved.