通过减少清单上的代码/操作的数量来优化方法

时间:2019-07-02 13:17:59

标签: java java-8

我想通过将操作合并为一个来减少开销,但是似乎还不太清楚如何正确地完成代码

目前,我有可以运行的代码:

public Map<String, Invoice> initialize(List<String> paths) {
    List<Invoice> invoices = paths
        .stream()
        .map(Invoice::new)
        .collect(Collectors.toList());

    invoices
        .forEach(e -> {
            e.setInvoiceInputStream(reader(e.getInvoicePath()));
            e.setInvoiceId(invoiceFinder.getInvoiceId(e.getInvoiceInputStream()));
        });

    Map<String, Invoice> invoiceMap = invoices
        .stream()
        .collect(
                Collectors.toMap(
                        e -> e.getInvoiceId(),
                        e -> e)
                );

return invoiceMap;

但是,执行此代码3次似乎是浪费时间。 如果我尝试其他类似的操作时遇到错误:

return invoicePaths
    .stream()
    .map(Invoice::new)
    .collect(
        Collectors.collectingAndThen(
            Collectors.toList(), list -> {
                list
                    .forEach(e -> {
                        e.setInvoiceInputStream(reader(e.getInvoicePath()));
                        e.setInvoiceId(invoiceFinder.getInvoiceId(e.getInvoiceInputStream()));
});

发票类中的构造函数:

public Invoice(String invoicePath) {
    this.invoicePath = invoicePath;
}

如何通过优化代码来减少开销?

2 个答案:

答案 0 :(得分:2)

 paths
    .stream()
    .map(Invoice::new)
    .map(e -> {
           e.setInvoiceInputStream(reader(e.getInvoicePath()));
           e.setInvoiceId(invoiceFinder.getInvoiceId(e.getInvoiceInputStream()));
           return e;

    })
    .collect(Collectors.toMap(
                  Invoice::getInvoiceId,
                  Function.identity())
            );

我希望我不会错过任何括号...

考虑一下,您正在收集List<Invoice> invoices只是为了forEach并更改某些内容-不是Stream::map操作吗?之后,您collect将它们添加到Map =>之后,只需继续流管道即可。

答案 1 :(得分:0)

您似乎没有在中间循环中做任何有用的事情-为什么不把它放在例如地图吗?

public Map<String, Invoice> initialize(List<String> paths) {
    return paths
        .stream()
        .map(path -> {
            Invoice e = new Invoice(path);
            e.setInvoiceInputStream(reader(e.getInvoicePath()));
            e.setInvoiceId(invoiceFinder.getInvoiceId(e.getInvoiceInputStream()));
            return e;
        })
        .collect(
                Collectors.toMap(
                        e -> e.getInvoiceId(),
                        e -> e)
                );
}```