代码
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<Item> 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<Item> items) {
System.out.println(items);
System.out.println();
System.out.println("==========分隔线==============");
System.out.println();
}
private static List<Item> sortV1(List<Item> items) {
return items.stream()
.sorted(Comparator
.comparing(Item::getA).reversed()
.thenComparing(Item::getB).reversed()
.thenComparing(Item::getC).reversed())
.collect(Collectors.toList());
}
private static List<Item> sortV2(List<Item> 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}]
==========分隔线==============