小工具知识网

当前位置: 首页 > 行业知识 > Java Stream流对多个字段动态指定字段排序

行业知识

Java Stream流对多个字段动态指定字段排序

2026-10-26 18:10:17 来源:互联网转载

    Java 8 的 Stream 使用了函数式编程模式,它可以被用来对集合或数组进行链状流式的排序就需要搬出Stream sort方法进行排序,重写其中的Comparator。

()

  本文重点介绍使用Java Stream流排序器Comparator对List集合进行排序的技巧,包括复杂实体对象多字段升降序排序方法。

()

1为什么采用函数式编程

     函数式编程(Functional Programming)是把函数作为基本运算单元,函数可以作为变量,可以接收函数,还可以返回函数。对函数实例的变量引用,就像对字符串、Map 或任何其他对象的引用一样。函数也可以作为参数传递给其他函数。

     利用Function把Java类中的get方法转换成Function形式,  用全局Map进行储存

    static public Map functionMap = new HashMap();     void init(T t) {        for (Method temp : t.getClass().getMethods()) {            String aaaa = temp.getName();            if (aaaa.startsWith("get")) {                System.out.println(aaaa);                String fieldName = aaaa.split("get")[1];                Function keyExtractosss11 = (a) -> {                    try {                        Object obj = temp.invoke(a, null);                        return obj;                    } catch (IllegalAccessException e) {                        e.printStackTrace();                    } catch (InvocationTargetException e) {                        e.printStackTrace();                    }                    return null;                };                functionMap.put(lowerFirst(fieldName), keyExtractosss11);            }        }    }

2 排序工具类方法

 static public  List sort(List userList, List fields) {        Function function = functionMap.get(fields.get(0));        Comparator comparator = null;        for (int i = 0; i  

3  示例

       定义一个Studen类,内部含有3个字段,调用调用sort方法可以动态实现对list集合多字段排序。

      Method[] getMethods = Student.class.getMethods();        List userList = new ArrayList();        Student student3 = new Student();        student3.setId(1);        student3.setName("1");        student3.setAddress("3");        userList.add(student3);        Student student1 = new Student();        student1.setId(1);        student1.setName("1");        student1.setAddress("2");        userList.add(student1);        Student student2 = new Student();        student2.setId(1);        student2.setName("1");        student2.setAddress("1");        userList.add(student2);        List fields = new ArrayList();        fields.add("id");        fields.add("name");        fields.add("address");        List userList111 = sort(userList, fields);        System.out.println(userList111);        for(Student temp:userList111){System.out.println("排序"+temp.getId()+";"+temp.getName()+";"+temp.getAddress());}

上一篇:揭秘绿色单词的英语发音技巧与解析

下一篇:服务器怎么设置电话转接?