Thursday, January 8, 2015

more hints regarding Optionals

Instead of
        Optional<Camera> camera = getCameraByMac(cameras, mac);        
        if (camera.isPresent()) {            
            return Optional.of( camera.get().getIp() );        
        } else {            
            return Optional.absent();        
        }

use
  
   Optional<Camera> camera = getCameraByMac(cameras, mac);
   return camera.transform(getIpFunction);

    static final Function<Camera, String> getIpFunction = new Function<Camera, String>() {
        @Nullable @Override
        public String apply(Camera camera) {
            return camera.getIP();
        }
    };

instead of
  
        List<Event> result = new LinkedList<>();
        for (Optional<Event> transformedEvent : someEvents) {
            if (transformedEvent.isPresent()) {
                result.add(transformedEvent.get());
            }
        }
        return result;

use
  
        return Optional.presentInstances(events);

No comments:

Post a Comment