4

Based in this Question...

I have this code:

List<IdDTO> ids = collectionEntityDTO.stream().map(EntityDTO::getId).collect(Collectors.toList());
List<Long> codes = ids.stream().map(IdDTO::getCode).collect(Collectors.toList());
Long[] arrayCodes = codes.toArray(new Long[0]);

How to do this, in this simple manner?

1 Answer 1

4

Your approach is rather inefficient, just chain the methods:

collectionEntityDTO.stream()
        .map(EntityDTO::getId)
        .map(IdDTO::getCode)
        .toArray(Long[]::new);

This approach is better because:

  • It’s easier to read what’s going on

  • It’s more efficient as already mentioned as doesn't require eagerly creating new collection objects at each intermediate step.

  • There's no clutter with garbage variables.
  • easier to parallelize.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.