可以在Lambda中执行此操作:
for (final WarehouseAddress address : warehouse.getAddresses()) {
if (!Validator.isEmpty(address.getPositions())) {
final Set<WarehouseAddressPosition> positions = new HashSet<WarehouseAddressPosition>(
address.getPositions());
if (address.getPositions().size() > positions.size()) {
throw new FieldDuplicatedException("position error");
}
}
}
我没有成功地试过这个:
final Set<WarehouseAddressPosition> positions = warehouse.getAddresses().stream().filter(a -> !Validator.isEmpty(a.getPositions())).collect(
Collectors.toSet());
因为他试图收集一套WarehouseAdress而不是一套WarehouseAdressPosition。
错误:(130,156)java:不兼容的类型:推理变量T有 不相容的界限 等式约束:br.com.erp.ejb.entity.sales.WarehouseAddressPosition 下界:br.com.erp.ejb.entity.sales.WarehouseAddress
在Warehouse类我有:
private List<WarehouseAddress> addresses;
在WarehouseAddress类中,我有:
private List<WarehouseAddressPosition> positions;
说明: 此代码获取原始位置列表并将其收集在Set中,以创建没有重复值的集合并将大小与原始列表进行比较,以检查它是否重复。由于Set不接受重复值,因此在这种情况下大小将不同。
答案 0 :(得分:7)
如果我理解正确,您希望收集WarehouseAddressPosition
,而不是WarehouseAddress
,因此您需要:
final Set<WarehouseAddressPosition> positions =
warehouse.
getAddresses().
stream().
filter(a -> !Validator.isEmpty(a.getPositions())).
flatMap(a -> a.getPositions().stream()).
collect(Collectors.toSet());
如果您希望在同一WarehouseAddressPosition
中遇到重复WarehouseAddress
时未通过此过程,我建议将private List<WarehouseAddressPosition> positions
更改为Set。这样,您可以在收集所有地址的位置之前找到此类重复项。
如果您有充分的理由不进行此更改,您可以在filter
步骤中进行相同的重复检查(目前在原始代码中完成)(我希望我的语法正确,因为我有现在没办法检查):
final Set<WarehouseAddressPosition> positions =
warehouse.
getAddresses().
stream().
filter(a -> if (!Validator.isEmpty(a.getPositions())) {
final Set<WarehouseAddressPosition> positions = new HashSet<WarehouseAddressPosition>(
a.getPositions());
if (a.getPositions().size() > positions.size()) {
throw new FieldDuplicatedException("position error");
} else {
return true;
}
} else {
return false;
}).
flatMap(a -> a.getPositions().stream()).
collect(Collectors.toSet());