List使用Stream流进行集合Collection的各种运算汇总:对BigDecimal求和,某个字段的和、最大值、最小值、平均值,字段去重,过滤等

       写Java接口的朋友都知道,Java 8的更新,经常会用到过滤 list<Object> 里的数据,本文就对List使用Stream流进行集合Collection的各种运算做一个汇总!

优势:

       Stream 是对集合(Collection)对象功能的增强,它专注于对集合对象进行各种非常便利、高效的聚合操作,或者大批量数据操作。

       通常我们需要多行代码才能完成的操作,借助于Stream流式处理可以很简单的实现。

各种Stream流操作:

  • 过滤soList中Object的Name字段为空的情况
List<Object> soList = Lists.newArrayList();
List<Object> list = soList.stream().filter(item -> item.getName() != null).collect(Collectors.toList()); 
  • 取soList列表根据对象某个字段 去重
 List<Object> soList = Lists.newArrayList()

//distinct() 去重  
List<Integer> maxDueDayList2 = soList.stream().map(Object::getMaxDueDay).distinct().collect(Collectors.toList());
  • 计算一个List对象中某个字段总和
int total = list.stream().mapToInt(User::getAge).sum();
//上下等同
int ageSum = userList.stream().collect(Collectors.summingInt(User::getAge));
  • 计算一个List对象中某个字段的和、最大值、最小值、平均值、总个数
double doublesum = listUsers.stream().mapToDouble(Users::getAge).sum();//和
int intmax = listUsers.stream().mapToInt(Users::getAge).max().getAsInt();//最大
int intmin = listUsers.stream().mapToInt(Users::getAge).min().getAsInt();//最小
double avg = listUsers.stream().mapToDouble(Users::getAge).average().getAsDouble();//平均

//计算一个number类型的List对象
Integer[] integerArray = {1, 3, 5, 10, 18};
List<Integer> list = new ArrayList<>(Arrays.asList(integerArray));
IntSummaryStatistics summaryStatistics = list.stream().mapToInt((s) -> s).summaryStatistics();

System.out.println("总和:" + summaryStatistics.getSum());
System.out.println("平均数:" + summaryStatistics.getAverage());
System.out.println("总个数:" + summaryStatistics.getCount());
System.out.println("最大值:" + summaryStatistics.getMax());
System.out.println("最小值:" + summaryStatistics.getMin());
  • Java集合对象中的一个字段对其进行排序
Collections.sort(list, (o1, o2) -> o1.getCustomerCount() - o2.getCustomerCount());
List<Integer> ss = new ArrayList<>();
Collections.sort(ss, (o1, o2) -> (o1 - o2));
  • 取出list对象中的一个属性 列
List<String> stIdList1 = stuList.stream().map(Student::getId).collect(Collectors.toList());
  • List使用Stream对BigDecimal求和方法
BigDecimal result = fileDatas.stream()
// 将user对象的age取出来map为Bigdecimal
.map(IpayRepayFileData::getTotalAmount)
// 使用reduce()聚合函数,实现累加器
.reduce(BigDecimal.ZERO,BigDecimal::add);

  reduce是一个终结操作,它能够通过某一个方法,对元素进行削减操作。该操作的结果会放在一个Optional变量里返回。可以利用它来实现很多聚合方法比如count,max,min等。 

       T reduce(T identity, BinaryOperator accumulator);
       第一个参数是我们给出的初值,第二个参数是累加器,可以自己用实现接口完成想要的操作,这里使用Bigdecimal的add方法 最后reduce会返回计算后的结果

大家如果还有其他list的操作欢迎评论补充!

原文地址:https://www.cnblogs.com/aitree/p/14301533.html