如何删除 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]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP