stream流-去重

针对基本数据类型集合

java 复制代码
public class DistinctDemo {



    public static void main(String[] args) {



        ArrayList<Integer> users = new ArrayList<>();

        users.add(1);

        users.add(2);

        users.add(127);

        users.add(127);

        users.add(128);

        users.add(128);

        users.add(-128);

        users.add(-128);

        users.add(-129);

        users.add(-129);



        users.stream().distinct().forEach(u -> System.out.println(u));

    }

}

针对对象集合

根据对象中的某一个成员变量进行去重

使用filter根据集合中对象的某个成员变量进行去重

java 复制代码
public class DistinctByVariableDemo {



    public static void main(String[] args) {



        ArrayList<User> users = new ArrayList<>();

        users.add(new User("小明", 1));

        users.add(new User("小力", 2));

        users.add(new User("小明", 3));

        users.add(new User("小为", 4));

        users.add(new User("小和", 5));



        users.stream().filter(distinctByVariable(Order::getOrderId)).

                forEach(fu -> System.out.println(fu.toString()));

    }



    /**

     * putIfAbsent() 方法是

     *      如果 key对应的value值不存在, key value 添加到 map 中,并返回 null

     *      如果 key对应的value值已存在, key value 不再添加到 map 中, 并返回原 value

     *

     * 故 newKey(这里的newKey对应user对象中的name的值), 如果(newKey, Boolean.TRUE) 在map中已存在,

     * putIfAbsent(newKey, Boolean.TRUE) 会返回 Boolean.TRUE (Boolean.TRUE 被final修饰,故其地址值唯一, 可用作比较)

     * 然后判断是否等于 null, 返回false, filter接收到结果为false的Predicate并将该值过滤掉

     * @param keyExtractor

     * @param <T>

     * @return

     */

    private static <T> Predicate<T> distinctByVariable(Function<? super T, ?> keyExtractor) {

        ConcurrentHashMap<Object, Boolean> map = new ConcurrentHashMap<>();

        return t -> map.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;

    }

}
相关推荐
寻星探路4 小时前
【深度长文】万字攻克网络原理:从 HTTP 报文解构到 HTTPS 终极加密逻辑
java·开发语言·网络·python·http·ai·https
想用offer打牌5 小时前
MCP (Model Context Protocol) 技术理解 - 第二篇
后端·aigc·mcp
曹牧7 小时前
Spring Boot:如何测试Java Controller中的POST请求?
java·开发语言
KYGALYX7 小时前
服务异步通信
开发语言·后端·微服务·ruby
掘了7 小时前
「2025 年终总结」在所有失去的人中,我最怀念我自己
前端·后端·年终总结
爬山算法7 小时前
Hibernate(90)如何在故障注入测试中使用Hibernate?
java·后端·hibernate
kfyty7258 小时前
集成 spring-ai 2.x 实践中遇到的一些问题及解决方案
java·人工智能·spring-ai
猫头虎8 小时前
如何排查并解决项目启动时报错Error encountered while processing: java.io.IOException: closed 的问题
java·开发语言·jvm·spring boot·python·开源·maven
李少兄8 小时前
在 IntelliJ IDEA 中修改 Git 远程仓库地址
java·git·intellij-idea