今天做总结的时候发现java 8 比较list中对象的相关参数最大值时方法有五种方法之多,做个总结记录一下:
话不多说上代码。
例子:
实体类:
public class Transaction {
private Trader trader;
private int year;
private int value;
public Transaction(Trader trader, int year, int value) {
this.trader = trader;
this.year =year;
this.value =value;
}
public Trader getTrader() {
return trader;
}
public void setTrader(Trader trader) {
this.trader = trader;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
最大值查询
方法1:返回最大值
OptionalInt highestValue = transactions.stream()
.mapToInt(Transaction::getValue)
.max();
方法2:返回拥有最大值的对象
Optional<Transaction> highestValue = transactions.stream()
.collect(Collectors.maxBy(transactionComparator));
方法3:返回最大值
Optional<Integer> lowestValue = transactions.stream()
.map(Transaction :: getValue)
.reduce(Integer::min);
方法4:返回拥有最大值的对象
Optional<Transaction> highestValue1 = transactions.stream()
.collect(Collectors.reducing(
(x,y) -> x.getValue() > y.getValue() ? x:y));
方法5:返回拥有最大值的对象
Comparator<Transaction> transactionComparator = Comparator.comparingInt(Transaction::getValue);
Optional<Transaction> highest =transactions.stream()
.collect(Collectors.maxBy(transactionComparator));
最小值方法类推。
方便以后使用