Search code examples
javacollectionsclosuresguavalambdaj

adding all results from running a method on elements in a collection to another collection


Is there a lambdaj way of doing this neatly? I know the title sounds complicated but the code fragment below should make it clear:

private List<String[]> getContractLineItemsForDatatables(List<ContractLineItem> contractLineItems) {

    List<String[]> contractLineItemsForDatatables = Lists.newArrayList();

    for (ContractLineItem contractLineItem : contractLineItems) {

        contractLineItemsForDatatables.add( contractLineItem.getDataTablesRow());
    }

    return contractLineItemsForDatatables;
}

There must be a neat way of doing this with Lambdaj to avoid the for loop above but I can't get my head around it. btw contractLineItem.getDatatablesRow() returns a String[].

So what I want to do is:

run getDataTablesRow() on all elements in contractLineItems list, and add them to contactLineItemsForDatatables list.

Any suggestions?


Solution

  • How about

    List<String[]> items = extract(contractLineItems, on(ContractLineItem.class).getDataTablesRow());
    

    LambaJ comes with a method named extract that is a mapper. You can also read the reference about converting objects with lambdaj.