Stream通道流支持两种排序方式:sorted()自然排序;sorted(Comparator comp)。
sorted()自然排序:产生一个新流,流中每个序列按自然排序的方式进行排序。 sorted(Comparator comp):产生一个新流,流中的每个序列按自定义的比较器排序进行排序
一、sorted()
public static void main(String[] args) throws InterruptedException {
List<String> list1 = new ArrayList<>();
list1.add("2");
list1.add("1");
list1.add("3");
Stream<String> stream1 = list1.stream().sorted();
stream1.forEach(p -> System.out.println(p));
}
输出结果
1
2
3
二、sorted(Comparator comp)
public static void main(String[] args) throws InterruptedException {
List<Order> list = new ArrayList<>();
Order order1 = new Order(LocalDateTime.now(), 1);
Thread.sleep(2000);
Order order2 = new Order(LocalDateTime.now(), 2);
Thread.sleep(2000);
Order order3 = new Order(LocalDateTime.now(), 3);
Thread.sleep(2000);
Order order4 = new Order(LocalDateTime.now(), 4);
list.add(order2);
list.add(order1);
list.add(order3);
list.add(order4);
Stream<Order> stream = list.stream().sorted((o1, o2) -> {
if (o1.getOrderTime().toInstant(ZoneOffset.of("+8")).toEpochMilli() - o2.getOrderTime().toInstant(ZoneOffset.of("+8")).toEpochMilli() >= 0) {
return o1.getOrderTime().compareTo(o2.getOrderTime());
} else {
return o1.getOrderTime().compareTo(o2.getOrderTime());
}
});
stream.forEach(p -> System.out.println(p));
}
输出结果
Order{orderTime=2018-08-09T15:59:28.458, orderId=1}
Order{orderTime=2018-08-09T15:59:30.460, orderId=2}
Order{orderTime=2018-08-09T15:59:32.461, orderId=3}
Order{orderTime=2018-08-09T15:59:34.461, orderId=4}
三、获取排序的第一个元素
public static void main(String[] args) throws InterruptedException {
List<Order> list = new ArrayList<>();
Order order1 = new Order(LocalDateTime.now(), 1);
Thread.sleep(2000);
Order order2 = new Order(LocalDateTime.now(), 2);
Thread.sleep(2000);
Order order3 = new Order(LocalDateTime.now(), 3);
Thread.sleep(2000);
Order order4 = new Order(LocalDateTime.now(), 4);
list.add(order2);
list.add(order1);
list.add(order3);
list.add(order4);
Stream<Order> stream = list.stream().sorted((o1, o2) -> {
if (o1.getOrderTime().toInstant(ZoneOffset.of("+8")).toEpochMilli() - o2.getOrderTime().toInstant(ZoneOffset.of("+8")).toEpochMilli() >= 0) {
return o1.getOrderTime().compareTo(o2.getOrderTime());
} else {
return o1.getOrderTime().compareTo(o2.getOrderTime());
}
});
Optional<Order> first = stream.findFirst();
System.out.println(first);
Order order = first.get();
System.out.println(order);
}
输出结果
Optional[Order{orderTime=2018-08-09T16:47:26.415, orderId=1}]
Order{orderTime=2018-08-09T16:47:26.415, orderId=1}