Stream 多字段排序

代码

import lombok.AllArgsConstructor;
import lombok.Data;

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

public class StreamSortDemo {
    public static void main(String[] args) {
        int length = 2;
        List items = new ArrayList<>();
        for (int a = 1; a <= length; ++ a) {
            for (int b = 1; b <= length; ++ b) {
                for (int c = 1; c <= length; ++ c) {
                    items.add(new Item(a, b, c));
                }
            }
        }

        print(items);
        print(sortV1(items));
        print(sortV2(items));
    }

    private static void print(List items) {
        System.out.println(items);

        System.out.println();
        System.out.println("==========分隔线==============");
        System.out.println();
    }

    private static List sortV1(List items) {
        return items.stream()
            .sorted(Comparator
                .comparing(Item::getA).reversed()
                .thenComparing(Item::getB).reversed()
                .thenComparing(Item::getC).reversed())
            .collect(Collectors.toList());
    }

    private static List sortV2(List items) {
        return items.stream()
            .sorted(Comparator
                .comparing(Item::getA, Comparator.reverseOrder())
                .thenComparing(Item::getB, Comparator.reverseOrder())
                .thenComparing(Item::getC, Comparator.reverseOrder()))
            .collect(Collectors.toList());
    }

    @Data
    @AllArgsConstructor
    public static class Item {
        private int a;
        private int b;
        private int c;

        @Override
        public String toString() {
            return "{" + a + ", " + b + ", " + c + '}';
        }
    }
}

输出:

[{1, 1, 1}, {1, 1, 2}, {1, 2, 1}, {1, 2, 2}, {2, 1, 1}, {2, 1, 2}, {2, 2, 1}, {2, 2, 2}]

==========分隔线==============

[{2, 1, 2}, {2, 1, 1}, {2, 2, 2}, {2, 2, 1}, {1, 1, 2}, {1, 1, 1}, {1, 2, 2}, {1, 2, 1}]

==========分隔线==============

[{2, 2, 2}, {2, 2, 1}, {2, 1, 2}, {2, 1, 1}, {1, 2, 2}, {1, 2, 1}, {1, 1, 2}, {1, 1, 1}]

==========分隔线==============

参考

  • lambda的(多字段)分页和排序 comparing,thenComparing的区别

你可能感兴趣的:(Stream 多字段排序)