List用法:根据对象属性排序、筛选、去重

废话:

太久没更博了,最近搞一个很lao的项目,非java语言,数据很乱(用到4、5个库),不想说太多(毕竟也是一个十年的项目了),每天下班只想睡觉,真的懒的更新博客了(是真的懒!)

因为项目使用webservice调用服务(没有直接操作数据库),主要是对数据做一些处理,这里贴一下List的一些使用。

1、根据bean属性筛选

class Example{
  private Integer id;
  private String name;
}

//这里就不具体示例了
List<Example> exampleList = new ArrayList<>

//根据bean属性筛选
 List<Example> filterList = exampleList .stream().filter(
                (Example  e) -> "name".equals(e.getName())
        ).collect(Collectors.toList());

//多个参数筛选
ArrayList<Example> collect= exampleList .stream().collect(
                    Collectors.collectingAndThen(
                            Collectors.toCollection(() -> new TreeSet<>(
                                            Comparator.comparing(r -> r.getDate() + "#" + r.getId() + "#" + r.getCategory())
                                    )
                            ), ArrayList::new));

2、根据bean属性去重

class Example{
  private Integer id;
  private String name;
}


//根据bean属性去重
 List<Example> examples = new ArrayList<>();

 List<Example> examList= new ArrayList<>();

 //方法调用
 examples .stream().filter(distinctByKey(p -> p.getId()))  //filter保留true的值
                .forEach(examList::add);


 public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
        Map<Object, Boolean> seen = new ConcurrentHashMap<>();
        //putIfAbsent方法添加键值对,如果map集合中没有该key对应的值,则直接添加,并返回null,如果已经存在对应的值,则依旧为原来的值。
        //如果返回null表示添加数据成功(不重复),不重复(null==null :TRUE)
        return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
    }

3、根据bean属性排序

class Example{
  private Integer id;
  private String name;
}

 List<Example> examples = new ArrayList<>();

examples .sort(new Comparator<Example>() {
            @Override
            public int compare(Exampleo1, Exampleo2) {
                //升序
                return o1.getId().compareTo(o2.getId());

                //降序
                //return o2.getId().compareTo(o1.getId());
            }
        });

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值