Java教程

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

本文主要是介绍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使用反射对列表进行排序的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!