Java8中的Stream流现如今是我们在开发过程中必用的一项技术,它与 java.io 包里的 InputStream 和 OutputStream 是完全不同的概念。

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

Stream API 借助于同样新出现的 Lambda 表达式,极大的提高编程效率和程序可读性。同时它提供串行和并行两种模式进行汇聚操作,并发模式能够充分利用多核处理器的优势,使用 fork/join 并行方式来拆分任务和加速处理过程。

为什么要用Stream

  • 有高效的并行操作
  • 有多种功能呢个性的聚合操作
  • 函数式编程,使代码更加简洁,提高编程效率

使用记录

处理List对象的某个属性转换成数组

1
2
3
4
BigDecimal[] ranchPriceList = ranchPriceTitles.get(0).getRanchPriceTitles()
.stream().map(RanchPriceTitle::getItemPrice).toArray(BigDecimal[]::new);
BigDecimal[] platformPriceList = priceValueList
.stream().map(PriceValue::getValPrice).toArray(BigDecimal[]::new);

将List封装对象的某个属性转换为以逗号分隔的字符串

1
2
3
String str = String.join(",", userList.stream().
map(User::getUserName).
collect(Collectors.toList()));

求平均数

1
2
3
4
5
6
7
8
//如果list中属性不为null且不为0才参与计算
Double allRanchAvgDValue = ranchPriceAvgList.stream().
filter(
d -> d.getAvgPrice() != null
&& d.getAvgPrice().compareTo(BigDecimal.ZERO) > 0)
.mapToDouble(x -> x.getAvgPrice().doubleValue()).average().getAsDouble();

BigDecimal allRanchAvg = BigDecimal.valueOf(allRanchAvgDValue);//牧场采购均价

将List中封装对象其中的属性作为Key值转为Map<String,Obj>

1
2
Map<String, ItemPrice> departmentMap = oldItemPrice.stream()
.collect(Collectors.toMap(x->x.getOrgCode()+"#"+x.getPrcDate(), Function.identity()));

根据List封装对象中的某个属性进行分组

1
2
Map<Integer, List<Department>> collect = departmentList.stream().
collect(Collectors.groupingBy(depart -> depart.getId()));

获取树形结构数据 -递归

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public List<MediaEntity> getAllFile() {
List<Long> resourceIds = resourceVisitorScopeService.getCanVisitorResourceIds(CategoryCode.LEARNING.getCode()
, ResourceVisitorScopeTypeCode.MEDIA.getCode(),
2, 1);

List<MediaEntity> allFiles = mediaDao.getFileOne(resourceIds);
List<MediaEntity> rootFile = allFiles.stream()
.filter(s->s.getParentId()==0)
.peek(s->s.setChildren(getChildren(s,allFiles)))
.collect(Collectors.toList());

return rootFile;
}

public List<MediaEntity> getChildren(MediaEntity mediaEntity,List<MediaEntity> allFiles){
List<MediaEntity> childList = allFiles.stream()
.filter(file->mediaEntity.getId()==file.getParentId())
.peek(s->s.setChildren(getChildren(s,allFiles)))
.collect(Collectors.toList());
return childList;
}