Java Stream 多个条件进行组合排序

在公司中使用的Jpa ,但是当时我写的是原生的语句,因为我想对其中的几列进行排序好(包含asc 和desc)进行输出

SELECT c FROM ExtendCommand c LEFT JOIN FETCH c.batchEntity WHERE c.status in ('PRE_STOCK_IN','STOCK_IN') and c.transferCenter in ('IT', 'IT-B') order by c.client desc, c.supplierIndex asc, c.supplier desc

但是考虑到代码的风格尽量一样,所以可以考虑查出来对应的list 之后再利用stream 进行排序,所以更改后的代码如下:

getEm().createQuery("SELECT c FROM ExtendCommand c LEFT JOIN FETCH c.batchEntity WHERE c.status in ('PRE_STOCK_IN','STOCK_IN') and c.transferCenter in ('IT', 'IT-B') order by c.client desc", ExtendCommand.class).getResultList().stream().sorted(Comparator.comparing(ExtendCommand::getSupplierIndex).thenComparing(ExtendCommand::getSupplier).reversed()).collect(Collectors.toList());

对应的测试:

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class SortListTest {
    @Test
    public void testSortList() {
        List list = new ArrayList();
        list.add(new Student(1, "Mahesh", 12));
        list.add(new Student(2, "Suresh", 15));
        list.add(new Student(3, "Nilesh", 10));
        list.add(new Student(4, "Nilesh", 15));

        System.out.println("---原始数据---");
        List slist = list;
        slist.forEach(e -> System.err.println("Id:" + e.getId() + ", Name: " + e.getName() + ", Age:" + e.getAge()));


        System.out.println("---按照年龄正序和(id倒序)---");
        slist = list.stream().sorted(Comparator.comparing(Student::getAge).thenComparing(Student::getId).reversed()).collect(Collectors.toList());
        slist.forEach(e -> System.err.println("Id:" + e.getId() + ", Name: " + e.getName() + ", Age:" + e.getAge()));


        System.out.println("---按照年龄倒序---");
        List slist1 = list;
        slist1 = list.stream().sorted(Comparator.comparing(Student::getAge).reversed()).collect(Collectors.toList());
        slist1.forEach(e -> System.err.println("Id:" + e.getId() + ", Name: " + e.getName() + ", Age:" + e.getAge()));
    }

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    private static class Student {
        private int id;
        private String name;
        private int age;
    }
}

你可能感兴趣的:(Java Stream 多个条件进行组合排序)