如何使用lamda表达式对list进行求和
作者:爱钓鱼的Java
这篇文章主要介绍了如何使用lamda表达式对list进行求和问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
使用lamda表达式对list进行求和
Lambda 表达式是 JDK8 的一个新特性,最近写项目中求和计算使用的较多,写篇文章记录下。
1、实体类List返回Integer类型求和
//根据id查询库存 List<ProductStock> list = productStockMapper.selectList(Wrappers.<ProductStock>lambdaQuery().in(Product::id, idList)) //查询所有库存总和 Integer qtySum = list.stream().mapToInt(ProductStock::getStockQty).sum();
2、Integer类型List返回Integer类型求和
//查询当前所有商品库存 List<Integer> stockList = productStockMapper.selectStock(); //查询所有库存总和 Integer stockSum = stockList .stream().mapToInt(Integer::intValue).sum();
3、实体类List返回Bigdecimal类型求和
//根据id查询库存 List<ProductStock> list = productStockMapper.selectList(Wrappers.<ProductStock>lambdaQuery().in(Product::id, idList)) //查询所有库存金额总和 BigDecimal stockAmt = list .stream().map(ProductStock::getStockAmt).reduce(BigDecimal::add).orElse(Bigdecimal.ZERO);
4、BigDecimal类List返回Bigdecimal类型求和
//查询当前所有商品库存 List<Bigdecimal> stockList = productStockMapper.selectStock(); //查询所有库存金额总和 Bigdecimal stockAmt = stockList.stream().reduce(BigDecimal::add).orElse(Bigdecimal.ZERO);
**注:orElse(Bigdecimal.ZERO)而不是get(),是因为防止返回空(此处如果用get(),在idea中也会有警告)。
最近用到的就这些,后续用到别的还会再更新!
list与Lamda表达式配合的常用方法
1、删除所有值为400的元素
list.RemoveAll(e=>e==400);
2、删除所有能被100整除的元素
list.RemoveAll(e=>e%100==0);
3、求和
int sum=0; int result = list.ForEach(val=>sum+=val);
4、删除所有值为400的元素
bool result = list.Exists(e=>e==400)
5、是否所有的元素都等于400
bool result = list.TrueForAll(e=>e==400)
6、返回能被100整除的元素(从前向后找)
var result = list.Find(e=>e%100==0);
6、返回能被100整除的元素(从后向前找)
var result = list.FindLast(e=>e%100==0);
7、返回能被100整除的List
var result = list.FindAll(e=>e%100==0);
8、返回能被100整除的索引(从前向后找)
int result = list.FindIndex(e=>e%100==0);
9、返回能被100整除的索引(从后向前找)
int result = list.FindLastIndex(e=>e%100==0);
10、二分查找(速度较快,它的原理是先把排序好的list分成2分,搜索中点值,发现值不对,就可以砍掉这个分组,只剩下一半再查找)
list.Sort();//二分查找前先必须先升序排序 int result = list.BinarySearch(e=>e%100==0);
11、对类(引用类型)进行排序(bookList.Sort()),需要类实现IComparable接口
internal class Book : IComparable<Book>
{
public int ID { get; set; }
public string Name { get; set; }
public double Price { get; set; }
public int CompareTo([AllowNull] Book other)
{
if (other == null) return 1;
return this.ID - other.ID;//返回正数,this>other;返回0,this=other;返回负数,this<other;
}
public override string ToString()
{
return JsonSerializer.Serialize(this);
}
public override bool Equals(object obj)
{
if (obj == null) return false;
Book other = obj as Book;
if (other.ID == this.ID && other.Name == this.Name && other.Price == this.Price) return true;
return false;
}
}12、对类(引用类型)进行二分查找(bookList.BinarySearch()),只能查找相应对象。如果只查找属性一致的对象,需重写Equals()方法,如上所示。
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
