List的一些常用处理

发布于 2022年 05月 19日 01:28

List 中的一些操作

A替换为自己的类

List普通分组

List<A> aList = new ArrayList<>();
//根据year进行分组
Map<String, List<A>> yearPsTitle = title1s.stream().collect(Collectors.groupingBy(A::getYear));

List分组后取一条数据

List<A> aList = new ArrayList<>();
//根据id划分组
Map<Long, A> map = jxBases.stream().collect(Collectors.toMap(A::getId, Function.identity(), (exiting, replacement) -> exiting));

List转tree

public static void main(String[] args) {
    //所有节点
    List<A> aAll = new ArrayList<>();
    //根节点
    List<A> topNode = aAll.stream()
        .filter(t -> t.getParentId == 0).collect(Collectors.toList());
    List<A> result = topNode.stream()
            .map(t -> covert(t, aAll)).collect(Collectors.toList());
}
private static A covert(A a, List<A> aList) {
    A node = new A();
    BeanUtils.copyProperties(a, node);
    List<A> children = aList.stream()
            .filter(t -> t.getParentId().equals(a.getId()))
            .map(t -> covert(t, aList)).collect(Collectors.toList());
    node.setChildren(children);
    return node;
}

List转tree后过滤

 /**
  * 递归 过滤
  * @param aList 必须为树结构
  * @param tiaojian A的某个属性符合tiaojian
  * @return 返回符合条件的数据
  */
 private List<A> diguiFilter(List<A> aList, String tiaojian) {
    if (StringUtils.isEmpty(tiaojian)) {
        return aList;
    }
    if (aList.size() == 0) {
        return new ArrayList<>();
    }
    List<A> result = new ArrayList<>();
    for (int i = 0; i < aList.size(); i++) {
        boolean match = tiaojian.equals(aList.get(i).getTiaojian());
        if (match){
            result.add(aList.get(i));
            continue;
        }
        if (diguiFilter(aList.get(i).getChildren(), tiaojian).size() > 0) {
            A a = new A();
            BeanUtils.copyProperties(aList.get(i), a);
            a.setChildren(diguiFilter(aList.get(i).getChildren(), tiaojian));
            result.add(a);
        }
    }
    return result;
}

List 钉钉发送消息的处理

因为钉钉消息一次最多发送100个人,所以list大于100时可以调用该方法

public static void main(String[] args) {
    List<String> ddIds = new ArrayList<>();
    for (int i = 1; i <= 10; i++) {
        ddIds.add("测试:" + i);
    }
    double size = ddIds.size();
    //一次循环遍历的数量
    int maxSize = 4;
    //循环次数
    int num = new BigDecimal(size / maxSize).setScale(0, RoundingMode.UP).intValue();
    for (int i = 0; i < num; i++) {
        List<String> ddId100 = ddIds.stream().skip(maxSize * i).limit(maxSize).collect(Collectors.toList());
        String ddId = String.join(",", ddId100);
        System.out.println(ddId);
    }
}

推荐文章