比较器的「退化」

比较器的「退化」


Java「语法糖」越来越牛逼了哈。

在使用匿名内部类比较器的时候,idea提供了几个层次的比较器代码优化,给👴整懵逼了。

Here is the original code:

 1 // sort by time
 2barList.sort(new Comparator<MarketDataBar>() {
 3    @Override
 4    public int compare(MarketDataBar o1, MarketDataBar o2) {
 5        if (o1.getTime().getTime() > o2.getTime().getTime()) {
 6            return 1;
 7        }
 8        if (o1.getTime().getTime() < o2.getTime().getTime()) {
 9            return -1;
10        }
11        return 0;
12    }
13});

Firstly, we could use Long.compare() to replace the if statement, it looks like:

1// sort by time
2barList.sort(new Comparator<MarketDataBar>() {
3    @Override
4    public int compare(MarketDataBar o1, MarketDataBar o2) {
5        return Long.compare(o1.getTime().getTime(), o2.getTime().getTime());
6    }
7});

So far, the code is much simplified then before.

But also, we coulde use lamda replace anonymous innner class, after doing that, it looks like:

1// sort by time
2barList.sort((o1, o2) -> Long.compare(o1.getTime().getTime(), o2.getTime().getTime()));

though we used lambda, we could replace the comparator with Comparator.comparingLong:

1// sort by time
2barList.sort(Comparator.comparingLong(o -> o.getTime().getTime()));

this is the ultimate version of a comparator, a 'one line compartor'.