Local-Variable Type Inference Java 10 Example

Java 9 legacy code:


@Test
public void java9Legacy() {
    Map<String, String> devs = new HashMap();
    devs.put("duke", "java8");
    for (Map.Entry<String, String> dev : devs.entrySet()) {
        System.out.println(dev.getKey() + " " + dev.getValue());
    }
}

...can be streamlined with Java 10 and Local-Variable Type Inference (JEP-286):


import java.util.HashMap;
import java.util.Map;
import org.junit.Test;

public class VariableTypeInferenceTest {

    @Test
    public void inferTypeWithJava10() {
        var modernDevs = new HashMap<String, String>();
        modernDevs.put("duke", "java10");
        for (var dev : modernDevs.entrySet()) {
            System.out.println(dev.getKey() + " " + dev.getValue());
        }
    }
}

The code above runs on openJDK 10 GA JDK 10, was edited with Apache Netbeans 9 and built with Maven 3.5.0


        <project>
        <modelVersion>4.0.0</modelVersion>
        <groupId>com.airhacks</groupId>
        <artifactId>variable-type-inference</artifactId>
        <version>1.0-SNAPSHOT</version>
        <packaging>jar</packaging>
        <dependencies>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.12</version>
                <scope>test</scope>
            </dependency>
        </dependencies>
        <properties>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
            <maven.compiler.source>10</maven.compiler.source>
            <maven.compiler.target>10</maven.compiler.target>
        </properties>
    </project>    

See you at Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting. Is Munich's airport too far? Learn from home: airhacks.io.


NEW MUC Airport Workshop: Migrating Java Client (Swing / Java FX) to Web Standards

Airport MUC workshops: Web (SPA, PWAs, Offline, Desktop, Mobile) Applications Essentials and Effective Web Applications. No migrations. #usetheplatform

Podcast: airhacks.fm and newsletter: airhacks.news

A book about rethinking Java EE Patterns

Comments:

What is Apache Netbeans and how it relared to old Netbeans? What is reason of migration?

Posted by Michal on April 12, 2018 at 10:27 AM CEST #

"Java 9 legacy code" ... I feel so old now :-)

It's quite interesting to see Java gaining pace!

Posted by Marco on April 17, 2018 at 07:23 AM CEST #

Post a Comment:
  • HTML Syntax: NOT allowed
realworldpatterns.com
Online Workshops
...the last 150 posts
...the last 10 comments
License