java list 对象去重
时间: 2023-08-30 09:09:34 浏览: 101
可以使用 HashSet 来实现去重,将 List 转换成 Set,再转回 List 即可。代码示例:
```java
List<String> list = new ArrayList<>();
list.add("a");
list.add("b");
list.add("c");
list.add("a");
list.add("b");
Set<String> set = new HashSet<>(list);
list.clear();
list.addAll(set);
System.out.println(list); // [a, b, c]
```
相关问题
javalist对象去重
以下是两种Java List对象去重的方法:
方法一:双重for循环去重
```java
public static void main(String[] args) {
List<Integer> list = new ArrayList<>(Arrays.asList(1, 1, 2, 3, 3, 3, 4, 5, 6, 6, 6, 7, 8));
for (int i = 0; i < list.size(); i++) {
for (int j = i + 1; j < list.size(); j++) {
if (list.get(i).equals(list.get(j))) {
list.remove(j);
j--;
}
}
}
System.out.println(list);
}
```
方法二:使用Java 8的Stream API去重
```java
public static void main(String[] args) {
List<Integer> list = new ArrayList<>(Arrays.asList(1, 1, 2, 3, 3, 3, 4, 5, 6, 6, 6, 7, 8));
List<Integer> listWithoutDuplicates = list.stream().distinct().collect(Collectors.toList());
System.out.println(listWithoutDuplicates);
}
```
java list对象去重
回答:
要在Java中对List对象进行去重,有几种常见的方法。其中一种方法是使用双重for循环遍历List,然后使用List的remove()方法去除重复项。具体代码如下所示:<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *3* [java List去除重复数据的五种方式](https://blog.csdn.net/m0_67900727/article/details/123422447)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"]
- *2* [Java对List中的对象去重](https://blog.csdn.net/zz0828zz/article/details/118694691)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文