Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

java8 list去重

作者:昨夜的风   发布日期:2025-09-02   浏览:54

import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.stream.Collectors;

public class ListDistinctExample {
    public static void main(String[] args) {
        // 创建一个包含重复元素的List
        List<String> listWithDuplicates = Arrays.asList("apple", "banana", "orange", "apple", "grape", "banana");

        // 方法1: 使用Stream API去重 (Java 8 及以上版本)
        List<String> distinctList = listWithDuplicates.stream()
                .distinct() // 去除重复元素
                .collect(Collectors.toList()); // 收集结果为List

        System.out.println("使用Stream API去重后的列表: " + distinctList);

        // 方法2: 使用LinkedHashSet去重 (保留原始顺序)
        List<String> distinctListUsingSet = listWithDuplicates.stream()
                .collect(Collectors.toCollection(LinkedHashSet::new)) // 使用LinkedHashSet去重并保持顺序
                .stream()
                .collect(Collectors.toList()); // 收集结果为List

        System.out.println("使用LinkedHashSet去重后的列表: " + distinctListUsingSet);
    }
}

解释说明:

  1. 创建包含重复元素的List:我们创建了一个包含重复字符串的 List,用于演示去重操作。
  2. 方法1 - 使用Stream API去重:通过 stream() 方法将 List 转换为流,然后使用 distinct() 方法去除重复元素,最后通过 collect(Collectors.toList()) 将结果收集回 List。此方法简单且易读。
  3. 方法2 - 使用LinkedHashSet去重:通过 collect(Collectors.toCollection(LinkedHashSet::new)) 将流中的元素收集到 LinkedHashSet 中,LinkedHashSet 不仅能去重,还能保持元素的插入顺序。然后再将其转换回 List

这两种方法都可以有效地去除 List 中的重复元素,具体选择哪种方法可以根据实际需求来决定。

上一篇:java aes解密

下一篇:idea java: 常量字符串过长

大家都在看

java连接数据库的代码

java djl

ubuntu 卸载java

java读取excel中的图片

java新建

java sort用法

java collections.sort

java file类的方法

java发送qq邮件

java 判断

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站