Java 8 - New Features

Java 8 - New Features

Parallel Array Sorting

We are used to sorting arrays with “Arrays.sort”. This used Merge Sort or Tim Sort algorithms for the sorting. The problem they have is that they are executed sequentially, so we do not gain all the benefits multithreading has to offer us. For this purpose they implemented “Arrays.parallelSort”.

When should we use this then?

We won’t gain direct benefits of using our 2 or more core processor right away.

The array should be of a certain size to see any gain in performance. Some comparisons say you will need around 2million elements in your array to start seeing improvements.



Base64 encoding and decoding

Not long ago I had to use Base64 encoding and decoding in a project to be able to transfer a file in JSON format.

I ended up using a 3rd party API (apache Base64 library) to do this .

This feature means we don’t have to search around for other implementations, making things a bit easier.

Some basic decoding and encoding examples

Encoding

String base64 = Base64.getEncoder().encodeToString("string to encode".getBytes("utf-8"));        

Decoding

byte[] asBytes = Base64.getDecoder().decode("your base 64 string");        


Date and time API

This is probably one of the features I am most excited about.

Dealing with dates and times in Java has always been a pain. We went from the now mostly deprecated methods in the Date class, remembering if Monday is represented as a 0 or a 1, the addition of the Calendar class to deal with timeZones and so on…

This made us use Joda Time or some other API to make things simpler. This won’t be necessary anymore.

The new API is very similar to Joda Time, so if you are already familiar with it you should catch things on the fly. If you never dealt with Joda Time do not worry, it is really simple to use.

Some date and time examples

javax.time.Clock

Clock.systemUTC(); //current time of your system in UTC.
Clock.millis();//time in milliseconds from 1/1/1970.        

javax.tme.ZoneId

ZoneId zone = ZoneId.of(“Europe/London”);//zoneId from a timezone.
Clock clock = Clock.system(zone);//set the zone of a Clock.        

javax.time.LocalDate

LocalDate?date?=?LocalDate.now();//current date
String?day?=?date.getDayOfMonth();//day of the month
String?month?=?date.getMonthValue();//month
String?year?=?date.getYear();//year        

Functional interfaces

A functional interface is the one that defines exactly one abstract method. We have for instance “java.lang.Runnable” defining the run abstract method:

public abstract void run();        

We can still add as many default methods (non abstract) as we like.

While defining a new functional interface, we will have to define the new annotation “@FunctionalInterface”. This will allow us to block bad usages of functional interfaces as it will not compile if used improperly with the new annotation.


Lambda expressions

Lambda expressions might be the biggest and most anticipated feature of Java 8. They are basically used to pass code instead of objects to a method or to deal with group of data to execute algorithms.

This will produce much simpler and more readable code. Lets take a look at some concepts around this.

Internal or External Iterations

The normal approach in Java is to iterate collections externally, so we would have something like this:

for (String value: myCollection) {
		System.out.println(value);
	}        

What we are doing here is iterating the list and pulling objects one by one. It would be more natural if we could just say from the beginning what we want to extract form the collection. This is exactly the concept of how we would do it with lambdas:

myCollection.forEach((String value) -> System.out.println(value));        

Passing Behaviours

This is for me where we can really find potential in lambda expressions. We can pass behaviours to functions making basic functionality much more generic and greatly increasing usability in our project.

For instance, if we want to create a method that prints all the elements of a List<String> we would do the following:

public void printAllStrings (List listString) {
		for(String stringObject : listString) {
			System.out.println(stringObject);
		}
	}        

If we now wanted to print only the strings that are longer than 4 characters long:

public void printLongerThan4Strings (List listString) {
		for(String stringObject : listString) {
			if(stringObject.length() > 4) {
				System.out.println(stringObject);
			}	
		}
	}        

In Java 8 we can make this process more generic and reuse more of our code. We can pass a predicate to do the filtering. It would look something like this:

public void printAllStrings (List listString, Predicate p) {
		for(String stringObject : listString) {
			if(p.test(stringObject)) {
				System.out.println(stringObject);
			}	
		}
	}        

Now all we have to do is pass the predicate in the call:

printAllStrings(listString, s ->?true);
printAllStrings(listString, s ->?s.length() > 4);        

Clean, fast and reusable.

要查看或添加评论,请登录

Ahmed El-Sayed的更多文章

  • Open System Architecture

    Open System Architecture

    "Open System Architecture" typically refers to the design and implementation of systems using open standards, open…

  • ChatGPT: Revolutionizing Conversational AI

    ChatGPT: Revolutionizing Conversational AI

    Artificial intelligence (AI) has come a long way in recent years, and one of the most exciting developments in this…

  • Togaf 9.2 Level 1 (Part 1)

    Togaf 9.2 Level 1 (Part 1)

    efore we go in details , we have to know how can we read the open group standards document, you should download the…

    1 条评论
  • Kafka vs RabbitMQ

    Kafka vs RabbitMQ

    What’s the Difference Between a Message Broker and a Publish/Subscribe (Pub/Sub) Messaging System? Message brokers are…

  • What is the strangler pattern and how does it work?

    What is the strangler pattern and how does it work?

    What is the strangler pattern? Picture a motorcycle that works, but could stand to undergo extensive overhauls that…

  • MIGRATING FROM MONOLITH TO MICROSERVICES: STRATEGY & STEP-BY-STEP GUIDE

    MIGRATING FROM MONOLITH TO MICROSERVICES: STRATEGY & STEP-BY-STEP GUIDE

    Migrating from monolith to microservices is less costly and risky than redeveloping an entire system from scratch. But…

    1 条评论
  • Migrate a monolith application to microservices using DDD

    Migrate a monolith application to microservices using DDD

    A monolithic application is typically an application system in which all of the relevant modules are packaged together…

    1 条评论
  • Migrate From Monolithic To Microservices Using DDD Pattern

    Migrate From Monolithic To Microservices Using DDD Pattern

    The general migration approach has three steps: Stop adding functionality to the monolithic application Split the…

  • Migrate From Monolithic To Microservices Using Strangler Pattern

    Migrate From Monolithic To Microservices Using Strangler Pattern

    There are three steps to transition from a monolithic application to microservices by implementing the Strangler…

  • GraalVM

    GraalVM

    GraalVM has caused a revolution in Java development since it launched three years ago. One of the most discussed…

社区洞察

其他会员也浏览了