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;

    }

}
相关推荐
于先生吖几秒前
Java+SpringBoot 无人健身房物联网系统完整源码实现
java·spring boot·物联网
johnrui20 分钟前
SpringBoot-JdbcTemplate
java·spring boot·后端
码云社区22 分钟前
JAVA二手车交易二手车市场系统源码支持微信小程序+微信公众号+H5+APP
java·开发语言·微信小程序·二手交易·闲置回收
crescent_悦23 分钟前
C++:The Largest Generation
java·开发语言·c++
indexsunny35 分钟前
互联网大厂Java面试实战:从Spring Boot到微服务的技术问答解析
java·spring boot·redis·微服务·消息队列·电商
Victor3561 小时前
MongoDB(72)如何创建用户和角色?
后端
Victor3561 小时前
MongoDB(71)如何启用MongoDB身份验证?
后端
想打游戏的程序猿1 小时前
工具与协议层——Agent 如何连接世界
后端·ai编程
希望永不加班2 小时前
SpringBoot 过滤器(Filter)与请求链路梳理
java·spring boot·后端·spring
Lyyaoo.2 小时前
【JAVA基础面经】抽象类/方法与接口
java·开发语言