Useful Java Language Features : Version 11 to 14

For product releases after Java SE 8, Oracle would designate a release, every three years, as a Long-Term-Support (LTS) release. Java SE 11 is an LTS release.  Based on the Oracle Java SE Support Roadmap, Java SE 12 to 15 are non-LTS releases that are more about incremental updates rather than major ones.  At the time of writing, the latest stable Java SE release is version 14.  This release is non-LTS.

While the Open JDK community project has their latest release, version 14, available for download,  Amazon offers their latest Corretto JDK, version 11, also for free.  There are other JDK providers offering version 11 and/or 14 as well.

Here are some examples to help understanding some of the language features from Java 11 to 14.

Java 11: var declaration in Lambda expression

// Java 11: var declaration in lambda expression

UnaryOperator<Integer> square = (@NonNull var x) -> x * x;
// var can be used with annotation such as @NonNull

System.out.println("x square is: " + square.apply(10));

Output:

x square is: 100

Java 11: HttpClient

// Java 11: HttpClient

Consumer <String> showHttpResponse = (link) -> {
    var httpClient = HttpClient.newHttpClient();
    try {
        var url = new URL(link);
        var httpRequest = HttpRequest.newBuilder().GET().uri(url.toURI()).build();
        var httpResponse = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());
        System.out.println("httpResponse quick check: " + httpResponse.toString());

    } catch (URISyntaxException | InterruptedException | IOException e) {
        e.printStackTrace();
    }
};

showHttpResponse.accept("https://www.google.ca");

Output:

httpResponse quick check: (GET https://www.google.ca) 200

Java 11: Various new methods in String class

// Java 11: Various new methods in String class

Consumer<String> testVariousStringMethods = (t) -> {
    System.out.printf("text is blank?: [%s]%n", t.isBlank());
    System.out.printf("trimmed text (old way): [%s]%n", t.trim());     // trim is the old method before Java 11
    System.out.printf("Stripped text: [%s]%n", t.strip());             // strip can work with unicode; trim cannot
    System.out.printf("Repeat text twice: [%s]%n", t.repeat(2));
};

String text = "\u2000  my test string  \u2000";
testVariousStringMethods.accept(text);

Consumer<String> getTextLineByLine = (t) -> {
    System.out.println("text line by line: ");
    t.lines().forEach(System.out::println);
};

text = "my test string\nhere is second line\nhere is third line\n";
getTextLineByLine.accept(text);

Output:

text is blank?: [false]
trimmed text (old way): [?  my test string  ?]
Stripped text: [my test string]
Repeat text twice: [?  my test string  ??  my test string  ?]
text line by line: 
my test string
here is second line
here is third line

Java 11: Files.writeString and Files.readString

// Java 11: Files.writeString and Files.readString

Consumer<String> writeString = (content) -> {
    try {
        Files.writeString(Paths.get("filename.txt"), content, StandardOpenOption.CREATE);
    } catch (IOException e) {
        e.printStackTrace();
    }
};

writeString.accept("This is the file content.");

Function<File, String> readString = (file) -> {
    try {
        return Files.readString(file.toPath());
    } catch (IOException e) {
        e.printStackTrace();
        return "file reading failed";
    }
};

System.out.println("This is the content read from file: " + 
		readString.apply(new File("filename.txt")));

Output (in Console):

This is the content read from file: This is the file content.

Java 12: Collectors.teeing

// Java 12: Collectors.teeing

Function<List<Integer>, String> getRange = (numbers) -> {
    return numbers.stream().collect(Collectors.teeing(
            Collectors.minBy(Integer::compare),
            Collectors.maxBy(Integer::compare),
            (min, max) -> String.format("%s - %s", min.isPresent() ? min.get() : ""
                    , max.isPresent() ? max.get() : "" )));
};

List<Integer> numbers = Arrays.asList(1,2,3,4,5);
System.out.println("range of numbers: " + getRange.apply(numbers));

Output:

range of numbers: 1 - 5

Java 12: NumberFormat.getCompactNumberInstance

// Java 12: NumberFormat.getCompactNumberInstance

Function<Number, String> getCompactNumber = (number) ->
        NumberFormat.getCompactNumberInstance().format(number);

BiFunction<Number, Integer, String> getCompactNumberLocalStyle = (number, type) -> {
        Locale locale;
        NumberFormat.Style style;
        if (type == 0) {
            locale = Locale.CANADA_FRENCH;
            style = NumberFormat.Style.SHORT;
        }
        else {
            locale = Locale.CANADA_FRENCH;
            style = NumberFormat.Style.LONG;
        }
        return NumberFormat.getCompactNumberInstance(locale, style).format(number);
};


int number = 1_234_567_890;
System.out.println("formatted number: " + getCompactNumber.apply(number));
System.out.println("formatted number in Canadian French Short Form: " + getCompactNumberLocalStyle.apply(number, 0));
System.out.println("formatted number in Canadian French Short Form: " + getCompactNumberLocalStyle.apply(number, 1));

Output:

formatted number: 1B
formatted number in Canadian French Short Form: 1 G
formatted number in Canadian French Short Form: 1 milliard

Java 13 Preview: Formatted multiple lines text block

// Java 13 Preview: Formatted multiple lines text block

Supplier<String> getFormattedTextBlockExample = () -> {
    String textWithFormat =
            """
                {
                    "type":"%s"
                    "bedroom":"%d"
                    "bathroom":"%d"
                    "garage":"%d"
                }
            """;
    return String.format(textWithFormat, "condo", 2, 2, 1);
};

System.out.println("text block with format:\n" + getFormattedTextBlockExample.get());

Output:

text block with format:
    {
        "type":"condo"
        "bedroom":"2"
        "bathroom":"2"
        "garage":"1"
    }

Java 14: record

// Java 14: record

record ResidentialUnit (String type, int bedroom, int bathroom, int garage) {}

var ru1 = new ResidentialUnit("semi-detached", 4 ,3, 1);
var ru2 = new ResidentialUnit("townhouse", 3 ,3, 1);

System.out.println("Unit 1: " + ru1.toString());
System.out.println("Unit 2: " + ru2.toString());

Output:

Unit 1: ResidentialUnit[type=semi-detached, bedroom=4, bathroom=3, garage=1]
Unit 2: ResidentialUnit[type=townhouse, bedroom=3, bathroom=3, garage=1]

Java 14: Improved switch statement

// Java 14: improved switch statement

Function<String, Boolean> checkPaintColor = (colorName) -> {
    boolean preferredColor;
    switch (colorName) {
        case "smooth white", "creamy white", "calm white" -> preferredColor = true;
        default -> preferredColor = false;
    }
    return preferredColor;
};

System.out.println("calm white is a preferred color: " + checkPaintColor.apply("calm white"));

Output:

calm white is a preferred color: true

Java 14: Switch expression

// Java 14: switch expression

Function<String, Boolean> checkFloorType = (floorType) -> {
    return switch (floorType) {
        case "hardwood", "laminate", "engineering hardwood" -> true;
        default -> false;
    };
};

System.out.println("hardwood is a preferred floor type: " + checkFloorType.apply("hardwood"));

Output:

hardwood is a preferred floor type: true

Java 14: Switch expression with yield

// Java 14: switch expression with yield

Function<String, Boolean> checkWoodType = (woodType) -> {
    return switch (woodType) {
        case "maple", "birch", "red oak", "white oak", "bamboo", "walnut" -> {
            System.out.println("Please refer to the wood properties in the hardware store website.");
            yield true;
        }
        default -> false;
    };
};

System.out.println("walnut is a preferred wood type: " + checkWoodType.apply("walnut"));

Output:

Please refer to the wood properties in the hardware store website.
walnut is a preferred wood type: true

Comments

Popular posts from this blog

Finding Median by Stream

Factorial by Different Styles in Java

Reduction by Java Stream