java8新特性+反射动态获取数据

java8新特性+反射动态获取数据

在生产上我经常需要获取List集合里某个属性,我需要抽取出来作为一个List集合或者Map集合

例如下我需要抽取list集合里面的code,或者是需要code作为key,name作为vue

 List<AgentInfo> list = new ArrayList<>();
        AgentInfo agentInfo = new AgentInfo();
        agentInfo.setCode("abc");
        agentInfo.setName("hhhh");
        agentInfo.setPeriod("a");
        agentInfo.setType("");


        AgentInfo agentInfo1 = new AgentInfo();
        agentInfo1.setCode("abcd");
        agentInfo1.setName("hhh");
        agentInfo1.setPeriod("");
        agentInfo1.setType("");

        list.add(agentInfo);
        list.add(agentInfo1);

传统写法

我觉得不够优雅看起来也不够高级
1.如果过滤属性很多,是不是要写很多filter()不够优雅
2.代码臃肿
3.这样的写法很容易就能看懂,怎么体现java功底

  List<String> collect = AgentInfolist.stream()
                .filter(item -> item.getPeriod() != null || "".equals(item.getPeriod()))
                .filter(item -> item.getType() != null || "".equals(item.getType()))
                .map(AgentInfo::getCode)
                .collect(Collectors.toList());


Map<String, String> AgentInfoMap= list.stream()
                .filter(item -> item.getPeriod() != null || "".equals(item.getPeriod()))
                .filter(item -> item.getType() != null || "".equals(item.getType()))
                .collect(Collectors.toMap(AgentInfo::getCode, AgentInfo::getName));

反射新特性写法

封装成工具类,通过一行代码解决

/**
 * @Title: AgentInfo
 * @Author sn
 * @Package com.jy.manage.controller
 * @Date 2024/5/9 16:59
 * @description:
 */

@Data
public class AgentInfo {
    private String code;
    private String name;
    private String period;
    private String type;

}
public class ReflectionUtils {

    /**
     *
     * @param list 数据集合
     * @param tclass 数据类型
     * @param status 过滤字段是任意一个满足,还是全部满足
     * @param kFieldName 返回的key
     * @param vFieldName 返回的value
     * @param fieldFilter 过滤的字段
     * @param <T>
     * @return
     */
    private static <T> Map<String, String> getDataMap(List<T> list, Class<T> tclass,
                                                      Boolean status, String kFieldName,String vFieldName, String... fieldFilter) {
        // 假设我们要基于fieldName字段的值作为键和值来构建Map
        Map<String, String> map = list.parallelStream()
                .filter(item -> {
                    List<Boolean> rule = new ArrayList<>(); //获取需要过滤的字段是否为空
                    try {
                        // 获取item的fieldName字段的值
                        for (String fieldName : fieldFilter) {
                            Field field = tclass.getDeclaredField(fieldName);
                            field.setAccessible(true);
                            String value = (String) field.get(item);
                            rule.add(StringUtils.isBlank(value));
                        }

                        boolean f = rule.stream().anyMatch(aBoolean -> aBoolean.equals(Boolean.TRUE));
                        boolean b = rule.stream().allMatch(aBoolean -> aBoolean.equals(Boolean.TRUE));
                        // 过滤掉空值
                        return status ? b : f;

                    } catch (NoSuchFieldException | IllegalAccessException e) {
                        throw new RuntimeException(e);
                    }
                })
                .collect(Collectors.toMap(
                        item -> {
                            try {
                                // 使用fieldName字段的值作为键
                                Field field = tclass.getDeclaredField(kFieldName);
                                field.setAccessible(true);
                                return (String) field.get(item);
                            } catch (NoSuchFieldException | IllegalAccessException e) {
                                throw new RuntimeException(e);
                            }
                        },
                        item -> {
                            // 使用fieldName字段的值作为值,或者根据需求使用其他逻辑
                            try {
                                Field field = tclass.getDeclaredField(vFieldName);
                                field.setAccessible(true);
                                return (String) field.get(item);
                            } catch (NoSuchFieldException | IllegalAccessException e) {
                                throw new RuntimeException(e);
                            }
                        }
                ));

        return map;
    }

    /**
     *
     * @param list 数据集合
     * @param tclass 数据类型
     * @param status 过滤字段是任意一个满足,还是全部满足
     * @param kvFieldName 返回的key
     * @param fieldFilter 过滤的字段
     * @param <T>
     * @return
     */
    private static <T> List<String> getDataList(List<T> list, Class<T> tclass,
                                                Boolean status, String kvFieldName, String... fieldFilter) {
        // 假设我们要基于fieldName字段的值作为键和值来构建Map
        List<String> data = list.parallelStream()
                .filter(item -> {
                    List<Boolean> rule = new ArrayList<>();
                    try {
                        // 获取item的fieldName字段的值
                        for (String fieldName : fieldFilter) {
                            Field field = tclass.getDeclaredField(fieldName);
                            field.setAccessible(true);
                            String value = (String) field.get(item);
                            rule.add(StringUtils.isBlank(value));
                        }

                        boolean f = rule.stream().anyMatch(aBoolean -> aBoolean.equals(Boolean.TRUE));
                        boolean b = rule.stream().allMatch(aBoolean -> aBoolean.equals(Boolean.TRUE));
                        // 过滤掉空值
                        return status ? b : f;

                    } catch (NoSuchFieldException | IllegalAccessException e) {
                        throw new RuntimeException(e);
                    }
                })
                .map(item -> {
                    try {
                        // 使用kvFieldName字段的作为值
                        Field field = tclass.getDeclaredField(kvFieldName);
                        field.setAccessible(true);
                        return (String) field.get(item);
                    } catch (NoSuchFieldException | IllegalAccessException e) {
                        throw new RuntimeException(e);
                    }
                })
                .collect(Collectors.toList());

        return data;
    }

    public static void main(String[] args)  {
        List<AgentInfo> list = new ArrayList<>();
        AgentInfo agentInfo = new AgentInfo();
        agentInfo.setCode("abc");
        agentInfo.setName("hhhh");
        agentInfo.setPeriod("a");
        agentInfo.setType("");


        AgentInfo agentInfo1 = new AgentInfo();
        agentInfo1.setCode("abcd");
        agentInfo1.setName("hhh");
        agentInfo1.setPeriod("");
        agentInfo1.setType("");

        list.add(agentInfo);
        list.add(agentInfo1);

        Map<String, String> codeOrName = getDataMap(list, AgentInfo.class, false, "code","name", "period", "type");
        List<String> dataList = getDataList(list, AgentInfo.class, false, "code", "period", "type");


    	System.out.println("codeOrName:"+codeOrName);
        System.out.println("dataList:"+dataList);
    }

输出结果

在这里插入图片描述

  • 11
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值