java - 如何管理具有重叠范围的项目,根据值我得到匹配的项目
问题描述
假设我有以下项目(未分类):
A, with A.amount = 10
B, with B.amount = 100
C, with C.amount = 50
D, with D.amount = 50
现在对于items 中的每个唯一数量边界AB ,找到其范围包含 value 的项目并计算累积括号。所以:
AB=10 results in { A, B, C, D } -> cumulative bracket 210
AB=50 results in { B, C, D } -> cumulative bracket 200
AB=100 results in { B } -> cumulative bracket 100
它会像这样使用:
for (int AB : collectAmountBoundaries(items)) {
Collection<Item> itemsInBracket = findItemsForAB(items, AB);
// execute logic, calculations etc with cumulative bracket value for AB
}
现在我可以使用 vanilla Java 对所有这些进行编码,首先手动将项目集合转换为AB→cumulativeBracketValue或其他东西的映射。但是,由于我正在使用范围和重叠逻辑,因此我觉得某种干净的解决方案涉及NavigableMap、Range逻辑或一些聪明的东西应该是可能的(感觉像是一种常见的模式)。或者也许使用流来收集 groupingBy?
我现在没看到。关于如何干净地解决这个问题的任何想法?
解决方案
我认为,做一个简单的过滤器,然后将过滤后的结果添加到列表中并总计就足够了。
static ListAndCumalativeAmount getCR(List<Item> items, double amount) {
ListAndCumalativeAmount result = new ListAndCumalativeAmount();
items.stream().filter(item -> item.amount >= amount).forEach((i) -> {
result.getItems().add(i.name);
result.add(i.amount);
});
return result;
}
static class ListAndCumalativeAmount {
private List<String> items = new ArrayList<>();
private Double amount = new Double(0.0);
public List<String> getItems() {
return items;
}
public void add(double value) {
amount = amount + value;
}
public Double getAmount() {
return amount;
}
}
推荐阅读
- spring-batch - Spring批处理:多线程步骤错误配置
- java - 将 imageProxy 转换为位图时,cameraX 图像已关闭
- delegates - C# Reflection/NUnit - 位于对象实例的公共字段中的 Func 是私有的。为什么?我如何包装它以使其公开?
- grpc - java - 如何从java中的grpc请求中获取请求头?
- powerbi - 在 Power BI 中合并两个表
- javascript - 单击会不必要地进行两次 ajax 调用,并且在我刷新页面之前 DOM 不会更新
- azure-storage - 如何为 Azure Databricks 配置 Azure Storage Gen 2
- ocr - 如何在正在运行的程序窗口上执行 OCR
- apache-spark - 如何为 spark 作业确定更好的 spark.sql.shuffle.partitions 编号
- plot - 在八度图中更改轴的比例