使用java写一个list去除重复数组的代码
时间: 2023-12-10 15:41:56 浏览: 70
可以使用Java中的Set集合来去除重复的元素,然后再将Set转换成List。以下是示例代码:
```
import java.util.*;
public class RemoveDuplicatesFromList {
public static void main(String[] args) {
Integer[] arr = {1, 2, 2, 3, 4, 4, 5};
List<Integer> listWithDuplicates = Arrays.asList(arr);
System.out.println("List with duplicates: " + listWithDuplicates);
Set<Integer> setWithoutDuplicates = new HashSet<>(listWithDuplicates);
List<Integer> listWithoutDuplicates = new ArrayList<>(setWithoutDuplicates);
System.out.println("List without duplicates: " + listWithoutDuplicates);
}
}
```
该代码先将数组转换成List,然后使用HashSet来去除重复元素,最后再将Set转换成List。输出如下:
```
List with duplicates: [1, 2, 2, 3, 4, 4, 5]
List without duplicates: [1, 2, 3, 4, 5]
```
阅读全文