Java 12 – New features and enhancements

Java 12 (released on March 19, 2019) is latest version available for JDK. Let’s see the new features and improvements, it brings for developers and architects.

1. Collectors.teeing() in Stream API

A teeing collector has been exposed as a static method Collectors::teeing. This collector forwards its input to two other collectors before merging their results with a function.

teeing(Collector, Collector, BiFunction) accepts two collectors and a function to merge their results. Every element passed to the resulting collector is processed by both downstream collectors, then their results are merged using the specified merge function into the final result.

For example, in a given list of employees, if we want to find out the employee with maximum salary and minimum salary, we can do it in single statement using teeing collector.

SalaryRange salaryRange = Stream
            .of(56700, 67600, 45200, 120000, 77600, 85000)
            .collect(teeing(
                    minBy(Integer::compareTo), 
                    maxBy(Integer::compareTo), 
                    SalaryRange::fromOptional));

Read More : Collectors.teeing()

2. String API Changes

2.1. String.indent()

The indent method helps with changing the indentation of a String. We can either pass a positive value or a negative value depending on whether we want to add more white spaces or remove existing white spaces.

String result = "foo\nbar\nbar2".indent(4);

System.out.println(result);

//    foo
//    bar
//    bar2

Please note that the indent() method automatically adds a newline character if it hasn’t been provided yet. That’s to be expected and is a feature of the new method.

Each white space character is treated as a single character. In particular, the tab character "\t" (U+0009) is considered a single character; it is not expanded.

2.2. String.transform()

The transform() method takes a String and transforms it into a new String with the help of a Function.

In given example, we have a list of names. We are performing two operations (trimming white spaces and making all names camel-case) using transform() method.

 List<String> names = List.of(
		            	"   Alex",
		            	"brian");

List<String> transformedNames = new ArrayList<>();

for (String name : names) 
{
    String transformedName = name.transform(String::strip)
            					.transform(StringUtils::toCamelCase);

    transformedNames.add(transformedName);
}

2.3. String constants

Since Java 12, String class implements two additional interfaces java.lang.constant.Constable and java.lang.constant.ConstantDesc.

String class also introduces two additional low-level methods describeConstable() and resolveConstantDesc(MethodHandles.Lookup).

They are low-level APIs meant for libraries and tools providing bytecode parsing and generation functionality, for example, Byte Buddy.

Just to note, a Constable type is one whose values are constants that can be represented in the constant pool of a Java class file as described in JVMS 4.4, and whose instances can describe themselves nominally as a ConstantDesc.

resolveConstantDesc() is similar to describeConstable() with the difference being that this method returns an instance of ConstantDesc instead.

3. Files.mismatch(Path, Path)

Sometimes, we want to determine whether two files have the same content. This API helps in comparing the content of files.

mismatch() method compares two file paths and return a long value. The long indicates the position of the first mismatched byte in the content of the two files. The return value will be '–1' if the files are “equal.”

Path helloworld1 = tempDir.resolve("helloworld1.txt");

Path helloworld2 = tempDir.resolve("helloworld2.txt");

long diff = Files.mismatch(helloworld1, helloworld2);	//returns long value

4. Compact Number Formatting

Large numbers rendered by a user interface or a command-line tool are always difficult to parse. It is far more common to use the abbreviated form of a number. Compact number representations are much easier to read and require less space on the screen without losing the original meaning.

E.g. 3.6 M is very much easier to read than 3,600,000.

Java 12 introduces a convenient method called NumberFormat.getCompactNumberInstance(Locale, NumberFormat.Style) for creating a compact number representation.

NumberFormat formatter = NumberFormat.getCompactNumberInstance(Locale.US,
            											NumberFormat.Style.SHORT);

String formattedString = formatter.format(25000L);		//25K

5. Support for Unicode 11

In a time in which emojis play a crucial role in communicating on social media channels, it’s more important than ever to support the latest Unicode specification. Java 12 has kept pace and supports Unicode 11.

Unicode 11 adds 684 characters, for a total of 137,374 characters – and seven new scripts, for a total of 146 scripts.

6. Switch Expressions (Preview)

This change extends the switch statement so that it can be used as either a statement or an expression.

Instead of having to define a break statement per case block, we can simply use the arrow syntax. The arrow syntax semantically looks like a lambda and separates the case label from the expression.

With the new switch expressions, we can directly assign the switch statement to a variable.

boolean isWeekend = switch (day) 
{
	case MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY -> false;

	case SATURDAY, SUNDAY -> true;

	default -> throw new IllegalStateException("Illegal day entry :: " + day);
};

System.out.println(isWeekend); 	//true or false - based on current day

To use this preview feature, remember that we have to explicitly instruct the JVM during application startup using –enable-preview flag.

Drop me your questions related to these new API changes in Java 12.

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

1 thought on “Java 12 – New features and enhancements”

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.