实现说明
真正干活的是类 NaturalOrdering、Price和函数 compareTo、main,其余都是接线。
stream 管道把“做什么”(变换)与“何时做”(终端 collect)分开。
使用要点
- 每一步打印都带着自己的标签:
lowest:、highest:、distinct prices:。
常见问题
运行「Comparable 自然顺序与 compareTo」会打印什么?
文件本身就是完整程序,直接运行——输出行带有 lowest:、highest:、distinct prices: 这类标签。
签名一览:public int compareTo(Price other)
核心语句
List<Price> sortedList = quotes.stream().sorted().toList();
return Integer.compare(this.cents, other.cents);
代码示例
import java.util.List;
import java.util.TreeSet;
public class NaturalOrdering {
// compareTo 与 equals 一致(都只看 cents),TreeSet 的判重与排序才可预测
record Price(int cents) implements Comparable<Price> {
@Override
public int compareTo(Price other) {
// Integer.compare 防止减法比较在极端值下溢出
return Integer.compare(this.cents, other.cents);
}
}
public static void main(String[] args) {
List<Price> quotes = List.of(new Price(990), new Price(150), new Price(990), new Price(250));
TreeSet<Price> sorted = new TreeSet<>(quotes);
System.out.println("lowest: " + sorted.first().cents());
System.out.println("highest: " + sorted.last().cents());
System.out.println("distinct prices: " + sorted.size());
List<Price> sortedList = quotes.stream().sorted().toList();
System.out.println("all quotes: "
+ sortedList.stream().map(price -> String.valueOf(price.cents())).toList());
}
}