共計 714 個字符,預計需要花費 2 分鐘才能閱讀完成。
Java 中 List 去重的方法有以下幾種:
- 使用 Set:將 List 轉換為 Set,因為 Set 不允許有重復元素,所以會自動去重。然后再將 Set 轉換為 List。
List list = new ArrayList();
// 添加元素到 list 中
Set set = new HashSet(list);
List newList = new ArrayList(set);
- 使用 Java 8 的 stream()方法:使用 stream()方法將 List 轉換為 Stream 對象,然后使用 distinct()方法去重,最后使用 collect()方法將 Stream 轉換為 List。
List list = new ArrayList();
// 添加元素到 list 中
List newList = list.stream().distinct().collect(Collectors.toList());
- 使用 Apache Commons Collections 庫:使用
CollectionUtils.removeDuplicates()
方法去重。
List list = new ArrayList();
// 添加元素到 list 中
List newList = new ArrayList(CollectionUtils.removeDuplicates(list));
- 使用 Java 8 的 HashSet:使用 Java 8 的 HashSet 去重,然后再將 HashSet 轉換為 List。
List list = new ArrayList();
// 添加元素到 list 中
List newList = new ArrayList(new HashSet(list));
以上是幾種常見的方法,根據具體需求可以選擇適合的方法進行去重。
丸趣 TV 網 – 提供最優質的資源集合!
正文完