Click here to Skip to main content
15,885,546 members
Articles / Web Development

More Java 8 Goodies

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
30 Jun 2015CPOL 4.3K  
More Java 8 goodies

I did streams yesterday but let's touch on a couple fun points. Again, I am a little late to the party on this stuff but I doubt I am the only one.

Optional

Could this be the end of null pointer exceptions? This is a lot nicer way to default values and do null checks. If you follow my blog, you know I hate ternary operators due to their poor readability and this does away with that in case of default values.

Java
Optional<String> displayText = Optional.ofNullable(null);
System.out.println(
    "display text found? " + displayText.isPresent() );
System.out.println(
    "display text: " + displayText.orElseGet( () -> "n/a" ) );
System.out.println(
    displayText.map( text -> text.toUpperCase() ).orElse(" ") );

Interface Changes

I am not entirely sure about this one because the line between abstract class and interface is really blurry.

Default Methods

This can help with backwards compatibility when adding new methods to interfaces.

Java
public interface MouseTrap {
    // ...
    default void setTrap() {
       // ...
    }
 }

Static Methods

Java
private interface MouseTrapFactory {
    // Interfaces now allow static methods
    static MouseTrap createMouseTrap(String bait) {
    return new BetterMouseTrap(bait);
}

Native JavaScript Support

Since I haven't used it really yet, I don't want to just copy other peoples examples but now with Java 8 the native JavaScript engine that can be accessed with in is Nashorn (pr. "nass-horn"). The JavaScript you write can be executed from the command line (which can even call Java classes) or within Java classes.

Related Content

This article was originally posted at http://www.bobbylough.com/2015/05/java-8-goodies.html

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
Full stack Java engineer looking to enhance the quality of the code around me. Find out more about me at http://www.bobbylough.com

Comments and Discussions

 
-- There are no messages in this forum --