【问题标题】:Map Stream<> to an instance of @value class from Lombok tool从 Lombok 工具将 Stream<> 映射到 @value 类的实例
【发布时间】:2020-03-31 20:56:37
【问题描述】:

我在一次采访中遇到了一个有趣的问题: 构建一个聚合器,其中包含项目及其转换为 GBR 货币的价格总和。

给定 Product 对象的流(java.util.stream.Stream),定义为:

@Value
class Product{
   String name;
   BigDecimal price;
   String currency;
}

@value 来自 Lombok 工具,可以生成 toString、equals 和 hashCode。它具有所有字段的吸气剂和单个所有参数的构造函数)。

聚合器函数将 Stream 映射到 ItemsAggregate 的实例,定义如下:

@value
class ItemsAggregate{
   List<Item> products;
   BigDecimal total;
}

@Value
class Item{
   String name;
   BigDecimal price;
}

提供了一个 Exchange 接口,用于将“价格”转换为 GBR 使用 GBRExchange:

interface Exchange{
   Optional<BigDecimal> rate(String currency);
}

我现在能做的答案是:

public class itemsAggregator implements Exchange{
    private Exchange exchange;
    itemsAggregator(GBRExchange GBRExchange){
        this.exchange = GBRExchange;
    }

    ItemsAggregate aggregate(Stream<Product> products){
        ItemsAggregate result = new ItemsAggregate();
        result.products = products.stream().filter(0->o!=null).collect(products.getName() ->Collectors.toList());
        result.total = products.stream().filter(o->o.getPrice()>=0).mapToInt(o -> o.getPrice()).sum();
        result.total = exchange.rate(result.total);
        return result;
    }
    @value
    class ItemAggregate{
        List<item> products;
        BigDecimal total;
    }

    @value
    class Item{
        String name;
        BigDecimal price;
    }
}

对象是: 1. 完成聚合函数并得到 GBR 'total' 变量。 2. 处理 GBRExchange 的无效值,例如 null、empty 和negative,因为它可能是错误的。 3. 对 ItemsAggregate.aggregate() 的 null、空 Stream 等输入应该在映射之前返回空 Stream 而不是 null。

谁能给我一些提示来修复这个解决方案(因为我无法调试它),特别是关于第 2 点和第 3 点?而且我不确定我是否正确对待@Value 类。

非常感谢。

【问题讨论】:

    标签: java oop data-structures java-stream lombok


    【解决方案1】:

    您可能正在寻找类似的东西:

        ItemsAggregate aggregate(List<Product> products) {
            List<Item> items = products.stream()
                    .filter(Objects::nonNull)
                    .map(p -> new Item(p.getName(),p.getPrice()))
                    .collect(Collectors.toList());
            BigDecimal total = products.stream()
                    .filter(o -> o.getPrice().compareTo(BigDecimal.ZERO) < 0)
                    .map(p -> exchange.rate(p.getCurrency()).orElse(BigDecimal.ZERO).multiply(p.getPrice()))
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            return new ItemsAggregate(items,total);
        }
    

    【讨论】:

      猜你喜欢
      • 2020-03-07
      • 1970-01-01
      • 1970-01-01
      • 2012-04-03
      • 2010-10-19
      • 2020-09-20
      • 2014-11-30
      • 2016-06-05
      • 2019-12-02
      相关资源
      最近更新 更多