使用 Comparator 代替比较方法
Using Comparator instead compare method
我遇到这种情况:
Stock.stream
.max(this::my_method)
.map....
public int my_method(Stock stock1, Stock stock2) {
int total1 = get_sum(stock1);
int total2 = get_sum(stock2);
if (total1 == total2) {
return stock1.get_quantity() - stock2.get_quantity();
}
return total1 - total2;
}
public Integer get_sum(Stock stock) {
return stock.get_quantity() - stock.get_wasted();
}
有没有一种方法可以使用 Java 比较器来编写它,或者它适用于其他一些情况?
您可以将 Comparator
与 lambda 一起使用。例如。如果你有以下 class:
class Stock {
int price;
}
您可以将 max
与使用 price
的比较器一起使用,例如:
List<Stock> stocks; //list
Stock max = stocks.stream()
.max(Comparator.comparing((a) -> a.price))
.get();
我遇到这种情况:
Stock.stream
.max(this::my_method)
.map....
public int my_method(Stock stock1, Stock stock2) {
int total1 = get_sum(stock1);
int total2 = get_sum(stock2);
if (total1 == total2) {
return stock1.get_quantity() - stock2.get_quantity();
}
return total1 - total2;
}
public Integer get_sum(Stock stock) {
return stock.get_quantity() - stock.get_wasted();
}
有没有一种方法可以使用 Java 比较器来编写它,或者它适用于其他一些情况?
您可以将 Comparator
与 lambda 一起使用。例如。如果你有以下 class:
class Stock {
int price;
}
您可以将 max
与使用 price
的比较器一起使用,例如:
List<Stock> stocks; //list
Stock max = stocks.stream()
.max(Comparator.comparing((a) -> a.price))
.get();