首页 > 解决方案 > 如何管理具有重叠范围的项目,根据值我得到匹配的项目

问题描述

假设我有以下项目(未分类):

A, with A.amount = 10
B, with B.amount = 100
C, with C.amount = 50
D, with D.amount = 50

现在对于items 中的每个唯一数量边界AB ,找到其范围包含 v​​alue 的项目并计算累积括号。所以:

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或其他东西的映射。但是,由于我正在使用范围和重叠逻辑,因此我觉得某种干净的解决方案涉及NavigableMapRange逻辑或一些聪明的东西应该是可能的(感觉像是一种常见的模式)。或者也许使用流来收集 groupingBy

我现在没看到。关于如何干净地解决这个问题的任何想法?

标签: javarange

解决方案


我认为,做一个简单的过滤器,然后将过滤后的结果添加到列表中并总计就足够了。

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;
    }

}

推荐阅读