Get Array of Property, of Property (nested property) using stream Java 8

chepe lucho :

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?

Ousmane D. :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=77653&siteId=1