Is this code convertible to a lambda style?

Howard Lovatt howard.lovatt at gmail.com
Fri Dec 27 16:56:59 PST 2013


Hi Marcos,

I would make some small changes:

private static boolean hasChildAssociation(PropertyDescriptor d) {
    return DataFactory.getInstance().getMetadataReader(d.getReaderMethod().
getReturnType()).getCollectionDescriptors().stream()
        .anyMatch(c -> c.isChildAssociation(d)));
}

private static Property convertToPropertyOrNull(Optional<PropertyDescriptor>
d) {
  if (d.isPresent()) {
    return d.get().convertToProperty()
  }
  return null;
}

return getMetadataReader().getPropertyDescriptors().stream()
    .unordered() // Assuming that order is not important
    .parallel() // Assuming that there are a lot of Properties
    .filter(d -> d.getType() == PropertyType.ENTITY)
    .filter(ThisClass::hasChildAssociation)
    .findAny() // Potentially faster
    .map(ThisClass::convertToPropertyOrNull);

Cheers,

 -- Howard.



On 25 December 2013 02:21, Marcos Antonio <marcos_antonio_ps at hotmail.com>wrote:

> I'd been trying a little more and maybe this is the solution I was looking
> for (I haven't tested it yet).
>
> return getMetadataReader().getPropertyDescriptors().stream().
>     filter(d -> d.getType() == PropertyType.ENTITY).
>     filter(d ->
> DataFactory.getInstance().getMetadataReader(d.getReaderMethod().getReturnType()).
>         getCollectionDescriptors().stream().
>         anyMatch(c -> c.isChildAssociation(d))).
>     findFirst().
>     map(d -> d.convertToProperty()).
>     orElse(null);
>
> Does it look right?
>
> Thank you.
>
> Marcos
>
> ----------------------------------------
> > From: marcos_antonio_ps at hotmail.com
> > To: lambda-dev at openjdk.java.net
> > Subject: Is this code convertible to a lambda style?
> > Date: Tue, 24 Dec 2013 17:48:31 +0300
> >
> > I'm really having trouble trying to convert this piece of code to lambda
> style, which makes me think if it is even possible.
> >
> > Property getParent()
> > {
> > for (PropertyDescriptor parent :
> getMetadataReader().getPropertyDescriptors())
> > {
> > if (parent.getType() == PropertyType.ENTITY)
> > {
> > MetadataReader metadataReader =
> >
> DataFactory.getInstance().getMetadataReader(parent.getReaderMethod().getReturnType());
> > for (CollectionDescriptor collection :
> metadataReader.getCollectionDescriptors())
> > {
> > if (collection.isChildAssociation(parent))
> > {
> > return parent.convertToProperty()
> > }
> > }
> > }
> > }
> > return null;
> > }
> >
> > I think this code seems very simple but in trying to convert it I'm not
> able to keep the reference to the parent to later methods in the stream
> pipeline.
> >
> > Any help?
> >
> > Thank you.
> >
> > Marcos
> >
>
>


-- 
  -- Howard.


More information about the lambda-dev mailing list