Java8统计金额demo
代码语言:javascript复制package com.example.core.mydemo.java8;
public class GoodsPriceDTO {
private String goodName;
private Integer amount;
public String getGoodName() {
return goodName;
}
public void setGoodName(String goodName) {
this.goodName = goodName;
}
public Integer getAmount() {
return amount;
}
public void setAmount(Integer amount) {
this.amount = amount;
}
}
代码语言:javascript复制package com.example.core.mydemo.java8;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
public class GoodsTotalTest {
public static void main(String[] args) {
List<GoodsPriceDTO> goodsPriceDTOS = new ArrayList<GoodsPriceDTO>();
GoodsPriceDTO dto = new GoodsPriceDTO();
dto.setGoodName("Apple");
dto.setAmount(27);
goodsPriceDTOS.add(dto);
dto = new GoodsPriceDTO();
dto.setGoodName("Orange");
dto.setAmount(28);
goodsPriceDTOS.add(dto);
dto = new GoodsPriceDTO();
dto.setGoodName("Banana");
dto.setAmount(29);
goodsPriceDTOS.add(dto);
dto = new GoodsPriceDTO();
dto.setGoodName("Apple");
dto.setAmount(23);
goodsPriceDTOS.add(dto);
int amt = Optional.ofNullable(goodsPriceDTOS)
.orElseGet(ArrayList::new)
.stream()
.filter(x -> x != null && ("Apple".equals(x.getGoodName()))).mapToInt(GoodsPriceDTO::getAmount).sum();
System.out.println("amt=" amt);
}
}