Java 8 generic collections with optionals -


i have relatively simple looking problem trying solve. there doesn't seem intuitive way or, missing here.

consider method find main image , if none exists, return first image-

public image findmainimage(collection<? extends image> images) {     if (images == null || images.isempty()) return null     return images.stream()                  .filter(image::ismain)                  .findfirst()                  .orelse(images.iterator().next()) } 

i error - orelse(capture<? extends image>) in optional cannot applied

any direction on great.

one way fix use type parameter:

public <i extends image> findmainimage(collection<i> images) {     if (images == null || images.isempty()) return null;     return images.stream()                  .filter(image::ismain)                  .findfirst()                  .orelse(images.iterator().next()); } 

because (to compiler) optional has same type argument images.

and use capturing helper if wanted:

public image findmainimage(collection<? extends image> images) {     return findmainimagehelper( images ); }  private <i extends image> findmainimagehelper(collection<i> images) {     // ... } 

personally, use generic version because can e.g.:

list<imagesub> list = ...; imagesub main = findmainimage( list ); 

basically...the reasoning why doesn't compile keep doing this:

public image findmainimage(     collection<? extends image> images1,     collection<? extends image> images2 ) {     return images1.stream()                   .filter(image::ismain)                   .findfirst()                   .orelse(images2.iterator().next()); }

and in original example compiler doesn't need determine fact both stream , iterator come same object. 2 separate expressions reference same object captured 2 separate types.


Comments

Popular posts from this blog

jquery - How do you format the date used in the popover widget title of FullCalendar? -

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -