JDK8 stream常见用法
LIST去重
常规数组等
对象LIST
根据faid属性分组
List jjhzTlYaVoList = new ArrayList<>();
jjhzTlYaVoList =jjhzTlYaVoList1.stream().collect(collectingAndThen(
toCollection(
() -> new TreeSet<>(Comparator.comparing(JjhzTlYaVo::getFaid))
),
ArrayList::new
));
生成新对象
取每个属性
Set subJgIdSet = allSubSysZcjgList.stream().map(SysZcjg::getId).collect(Collectors.toSet());
同时去重
List jgbidList = cyglYbjgList.stream().map(o -> o.getId()).distinct().collect(Collectors.toList());
取多属性
注意方式,忽略细节
List jjhzTlYaVoList = new ArrayList<>();
List qyjxKhfaJbxxList = new ArrayList<>();
qyjxKhfaJbxxList=jjhzTlYaVoList.stream().map(k -> {
QyjxKhfaJbxx qyjxKhfaJbxx = new QyjxKhfaJbxx();
qyjxKhfaJbxx.setId(k.getFaid());
qyjxKhfaJbxx.setFamc(k.getFamc());
return qyjxKhfaJbxx;
}).collect(Collectors.toList());
LIST 转MAP
KEY重复 (k1, k2) -> k1)
Map<String, QyjxJxkhFakKhxm> qyjxJxkhFakKhxmMap = qyjxJxkhFakKhxmList.stream().collect(Collectors.toMap(x -> x.getZbbm(), x -> x, (k1, k2) -> k1));
LIST过滤stream().filter
返回list
List tmpYbjgHcxqList = cyglYbjgHcxqList.stream().filter(o -> o.getJgbid().equals(cyglYbjg.getId())).collect(Collectors.toList());
返回唯一
QyjxZbfl exsitQyjxZbfl = qyjxZbflList.stream().filter(o -> {
if (fldj == 1) {
return flmc.equals(o.getFlmc());
} else {
return fldj == o.getFldj() && flmc.equals(o.getFlmc()) && parentFlid.equals(o.getFid());
}
}).findFirst().orElse(null);
List分组 Collectors.groupingBy
Map<String, List> jjhzTlYaVoMapFaidChildren = jjhzTlYaVoList.stream().collect(Collectors.groupingBy(k -> k.getFaid() + “”));
List 求和 .reduce
BigDecimal jggfALl = khdxlist.stream().map(JjhzTlYaVo::getGzzdl).reduce(BigDecimal.ZERO, BigDecimal::add);
List排序 sorted
默认
1、 cyglHcpdtjXmList = cyglHcpdtjXmList.stream().sorted(Comparator.comparing(QyjxCyglHcpdtjXm::getXmsx)).collect(Collectors.toList());
2、 this.fields = this.fields.stream().sorted(Comparator.comparing(objects -> ((Excel) objects[1]).sort())).collect(Collectors.toList());
自定义排序方法
jZbVoList = tjZbVoList.stream().sorted(new Comparator() {
@Override
public int compare(QyjxFakZbszTjZbVo o1, QyjxFakZbszTjZbVo o2) {
return Double.compare(o2.getTjScore(), o1.getTjScore());
}
}).collect(Collectors.toList());