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);
    }
}

 

上一篇:Java8新特性-为什么使用Lambda表达式


下一篇:java8的lambda表达式学习笔记