• java8使用反射对列表进行排序


    public class Project{
    
        private String spaceId;
    
        private String spaceName;
    
        public String getSpaceId() {
            return spaceId;
        }
    
        public void setSpaceId(String spaceId) {
            this.spaceId = spaceId;
        }
    
        public String getSpaceName() {
            return spaceName;
        }
    
        public void setSpaceName(String spaceName) {
            this.spaceName = spaceName;
        }
    
        public String getField(String orderBy) throws NoSuchFieldException, IllegalAccessException {
            return getClass().getDeclaredField(orderBy).get(this).toString();
        }
    }
    import java.util.ArrayList;
    import java.util.Comparator;
    import java.util.List;
    import java.util.function.Function;
    import java.util.stream.Collectors;
    
    public class Test {
    
        public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
            List<Project> projects =new ArrayList<>();
            Project project =new Project();
            project.setSpaceId("1");
            project.setSpaceName("yu");
            Project project1 =new Project();
            project1.setSpaceId("2");
            project1.setSpaceName("yufangwu");
            projects.add(project);
            projects.add(project1);
    
            List<Object> list = projects.stream().sorted(Comparator.comparing(new Function<Project, String>() {
                @Override
                public String apply(Project project) {
                    try {
                        return project.getField("spaceId");
                    } catch (NoSuchFieldException e) {
                        e.printStackTrace();
                        return null;
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                        return null;
                    }
                }
            }).reversed()).collect(Collectors.toList());
            System.out.println(list);
        }
    }
  • 相关阅读:
    Axure学习二:基础教程
    Axure 学习一:基础知识详解参考文档
    iOS 加载动态库报错问题
    iOS 9 之 Spotlight框架
    iOS 之 新功能、扩展
    mysql慢查询
    php curl多线程抓取网页
    php读取qqwry.dat ip地址定位文件的类
    php比较加赋值语句
    yaf在windows7下32位的安装教程
  • 原文地址:https://www.cnblogs.com/XueTing/p/15503997.html
Copyright © 2020-2023  润新知