java - Iterating through only some members of an array -


(full disclosure: coming form ruby guy who's been away java while)

entity[] space;  class planet extends entity ...   class star extends entity ... 

the space[] array contains mixture of nulls, planets , stars. want access stars in array (which might none.)

what's elegant java way of doing it, without using instanceof

in java try avoid using arrays (because they’re pain in butt work with).

so, first step collection api represent array. list comes mind!

list<entity> entities = arrays.aslist(space); 

now, java 8 has introduced stream api.

entities.stream()     .filter(e -> e != null)     .filter(e -> e instanceof star)     .foreach(e -> dosomethingwithstar((star) e)); 

if want avoid using instanceof need give entity class way differentiate between stars , other objects. boolean isstar() method might achieve that:

entities.stream()     .filter(e -> e != null)     .filter(e -> e.isstar())     .foreach(e -> dosomethingwithstar((star) e)); 

however, has still same problem: type of stream still stream<entity> though know there stars in them.

other ways of converting entity star or nothing add void addstartolist(list<star> stars) method adds entity list if star doesn’t add if it’s not star.

list<star> stars = new arraylist<>(); entities.stream()     .filter(e -> e != null)     .foreach(e -> e.addstartolist(stars)); 

Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -