Optional and Lambda

This is a piece of code that I converted using Lambdas. It is using JMX but that is irrevelant.

I wanted to use this method initially. This is the JDK source.

    /**
     * Returns an {@code Optional} describing the specified value, if non-null,
     * otherwise returns an empty {@code Optional}.
     *
     * @param <T> the class of the value
     * @param value the possibly-null value to describe
     * @return an {@code Optional} with a present value if the specified value
     * is non-null, otherwise an empty {@code Optional}
     */
    public static <T> Optional<T> ofNullable(T value) {
        return value == null ? empty() : of(value);
    }

But once I used Lambda code I realized the API returns Optional<MemoryPoolMXBean>


	   Optional<MemoryPoolMXBean> mpx = Optional.empty();


//			   for (MemoryPoolMXBean pool : memoryBeans) {
//		       		l.debug(pool.getName());
//		               if (pool.getName().equals(METASPACE)) {
//		            	   mpx =  Optional.ofNullable(pool);
//		               }
//		       }
			   
			   mpx =
			   memoryBeans
			    .stream()
			    .filter(p ->
			        {
			       	l.debug(p.getName());
			        return p.getName().equals(METASPACE);
			        })
			        .findFirst();

I don’t want to delve too deep into this as it doesn’t break the code that calls this.

Leave a comment