知识记录

使用Stream流获取唯一一个或首个的操作

1
2
3
if (CollectionUtils.isNotEmpty(supplierList)) {
supplierList.stream().filter(s -> s.getSupplierCode().equals(resultData.getSupplierCode())).findFirst().ifPresent(s -> resultData.setSupplierName(s.getSupplierName()));
}

分组

1
Map<Integer, List<Apple>> groupBy = appleList.stream().collect(Collectors.groupingBy(Apple::getId));

List转Map

1
Map<Integer, Apple> appleMap = appleList.stream().collect(Collectors.toMap(Apple::getId, a -> a,(k1,k2)->k1));

total

1
BigDecimal totalMoney = appleList.stream().map(Apple::getMoney).reduce(BigDecimal.ZERO, BigDecimal::add);

groupBy 实现的 list 转 map

1
2
3
4
5
6
7
8
9
public static <T, K> Map<K, T> list2Map(@NonNull Collection<T> list, @NonNull Function<? super T, K> keyFunc) {
return list.stream().collect(Collectors.toMap(keyFunc, Function.identity(),
(u, v) -> {
throw new IllegalStateException(String.format("Multiple entries with same key,%s=%s,%s=%s",
keyFunc.apply(u), u,
keyFunc.apply(v), v));
},
HashMap::new));
}

去重

1
List<Player> newList = playerList.stream().collect(Collectors .collectingAndThen( Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Player::getName))), ArrayList::new)); newList.forEach(System.out::println);

创建空集合

1
Collections.emptyList()

获取集合最小值(为空添加默认值)

1
2
3
4
evaluateBaseEntry.getValue().stream()
.map(SupplierEvaluateBaseinfo::getSecretLevel)
.filter(Objects::nonNull)
.min(Comparator.comparing(Integer::valueOf)).orElse("5");

list对象两个属性相乘在相加

1
item.stream().map(p -> p.getQuantity().multiply(p.getUnitPrice())).reduce(BigDecimal::add).orElse(BigDecimal.ZERO)

Java Stream递归

1
2
3
4
5
6
7
8
9
10
11
12
13
/**
* Java Stream递归
* 当找不到子级权限的时候map操作不会再递归调用covert
*/
private UmsPermissionNode covert(UmsPermission permission, List<UmsPermission> permissionList) {
UmsPermissionNode node = new UmsPermissionNode();
BeanUtils.copyProperties(permission, node);
List<UmsPermissionNode> children = permissionList.stream()
.filter(subPermission -> subPermission.getPid().equals(permission.getId()))
.map(subPermission -> covert(subPermission, permissionList)).collect(Collectors.toList());
node.setChildren(children);
return node;
}

java stream 多属性过滤

1
2
3
4
5
6
7
List<SupplierEvaluationYear> filter = supEvaluationYearList.stream()
.distinct()
.filter(e -> !(supplierEvaluationYears.stream()
.map(y -> y.getSupplierId() + ":" + y.getPurchaseId() + ":" + y.getProductType() + ":" + y.getYear())
.collect(toList())
.contains(e.getSupplierId() + ":" + e.getPurchaseId() + ":" + e.getProductType() + ":" + e.getYear())))
.collect(toList());