java 获取多个类的字段合并去重

在做项目的时候遇到一个情况,是想要获取多个class的字段,然后合并去重,这种需求用java stream 来做最爽的。

  /**
     * 不要过滤的字段 name 姓名  id_card_number 身份证号 | creditor_principal 债权金额本金 voucher_number 凭证号
     *
     * @return 应该过滤的字段
     */
    private List<String> getFilterStr() {
        // 不要过滤的字段
        List<String> noFilterStr = Stream.of("name", "idCardNumber", "creditorPrincipal", "voucherNumber").collect(Collectors.toList());
        // 获取债权人个人信息所有字段
        Field[] arpCreditorField = ArpCreditor.class.getDeclaredFields();
        List<String> arpCreditorFieldList = Arrays.stream(arpCreditorField).map(field -> field.getName()).collect(Collectors.toList());
        // 获取债权人债权信息的所有字段
        Field[] arpCreditorInfoField = ArpCreditorInfo.class.getDeclaredFields();
        List<String> arpCreditorInfoFieldList = Arrays.stream(arpCreditorInfoField).map(field -> field.getName()).collect(Collectors.toList());
        Field[] baseField = BaseEntity.class.getDeclaredFields();
        List<String> baseFieldList = Arrays.stream(baseField).map(field -> field.getName()).collect(Collectors.toList());
        // 合并字段去重
        List<String> distinctField = Stream.of(arpCreditorFieldList, arpCreditorInfoFieldList, baseFieldList)
                .flatMap(Collection::stream)
                .distinct()
                .collect(Collectors.toList());
        // 去重 - 不要的字段 = 要过滤字段
        List<String> filterStr = distinctField.stream().filter(item -> !noFilterStr.contains(item)).collect(Collectors.toList());
        return filterStr;
    }

 1.用反射获取到类的所有字段信息。

2.用流合并去重。

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值