Java 12 features
There are some interesting and useful features available in Java 12. However some are in Preview stage, not for production use. All Preview features are labelled accordingly.
Compact Number Formatting
Java 12 comes with number formatter the CompactNumberFormat. It was designed to represent number in shorter form based on patterns provided by given locale.
NumberFormat shortNumber = NumberFormat.getCompatcNumberInstance(new Locale("en", "US"), NumberFormat.Style.SHORT);
shortNumber.format(1000);
output: 10k
Try what output you get when you try Style.LONG.
Teeing Collector in Stream API
Collector<T, ?, R> teeing(Collector<? super T, ?, R1> downstream1, Collector<? super T, ?, R2> downstream2, BiFunction<? super R1, ? super R2, R> merger)
Every element is processed by both the downstream collectors and their results are passed to merger function. The example of teeing collector is shown belowIf we want to calculate average from set of numbers, we can use this.
Stream.of(1,2,3,4,5,6).collect(
Collectors.teeing(Collectors.summingDouble(i->i), Collectors.counting(), (sum, count) -> sum/count));
Switch (Preview)
One thing I like the most is, Switch statement or expression is undergoing some changes in it's syntax to accommodate more readability and reduce verbosity in code. I hope it comes out more efficient, readable and more optimized in future releases.
Let's dive into Switch statement little bit which is available as Preview in Java 12
Before Java 12 switch looks like below
String WEEK_DAY;
case Monday:
case Tuesday:
case Wednesday:
case Thursday:
case Friday:
return "Business days";
case Saturday:
case Sunday:
return "Non Business days";
}
String dayOfWeek;
case Monday, Tuesday, Wednesday, Thursday, Friday -> return "Business days";
case Saturday, Sunday -> return "Non Business days";
}
switch(dayOfWeek) {
case Monday, Tuesday, Wednesday, Thursday, Friday -> {
// More logic if you wanna add
return "Business days";
}
case Saturday, Sunday -> return "Non Business days";
}
Comments
Post a Comment