gpt4 book ai didi

java - 通过减少列表上的代码/操作量来优化方法

转载 作者:行者123 更新时间:2023-12-02 01:26:24 25 4
gpt4 key购买 nike

我想通过将我的操作合并到一个操作中来减少开销,但似乎不太清楚如何在没有错误的情况下完成我的代码

目前我有这个有效的代码:

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

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

最佳答案

 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 => 之后继续流管道。

关于java - 通过减少列表上的代码/操作量来优化方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56853414/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com