I want to reduce overhead by merging my operations into one but don't seem to quite figure out how to complete my code without errors
Currently I have this code that works:
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;
However, executing this code 3 times seems a waste of time. If I try something different like I get errors:
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()));
});
Constructor in Invoice class:
public Invoice(String invoicePath) {
this.invoicePath = invoicePath;
}
How can I reduce and overhead by optimizing my code?