Posts

Showing posts with the label Java 8

In Detail:Collectors toList() method in Java 8

Introduction:          Collectors.toList() method is used to transform the java stream into a List of values. This process is called a reduction. The Collectors class implements various useful reduction operations such as accumulating the stream elements into collections etc.  In a simple layman terms, Collectors.toList() method is used to convert a stream of values to a List of values. Collectors.toList() actually returns a Collector object which accumulates/combines the input elements into a new List.  Now let us see how to implement Collectors.toList() with an example. Code Exmaple package test; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; public class CollectorsToList { public static void main(String[] args) { // create a sample list List&ltInteger&gt aList = new ArrayList&lt&gt(); // add few elements to the array list aList.add(1); aList.add(2); aList.add(3); a...

How to Convert Java 8 IntStream to a List

Image
1. Overview                     In this tutorial, we are going to convert an IntStream to List and to an array. IntStream is a stream of primitive int values and a List is an ordered collection that holds generic values. To convert a stream to the collection, we can call collect() method of Stream class, but this works when the streams hold non-primitive types. Calling collect() method on primitive streams give a compilation error "collect() in IntStream cannot be applied to". 2. Solutions 2.1. Call boxed() method before collecting to a List        IntStream has a method boxed() that returns a Stream consisting of the elements each boxed to an Integer. After getting a boxed stream, we can call the collect() method to convert into a List. Code: package streams; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; public class IntStreamTest { public stati...

Inner Classes & Nested Classes Java

As per java documentation An inner class is a non static class declared inside another class. A nested class is a static class declared inside another class, Even though it is declared inside another class, it won't be considered as an inner class. Some tricky points to remember: It is a compile-time error if an inner class declares a member that is explicitly or implicitly static, unless the member is a constant variable. A constant variable is a final variable of primitive type or type "String" that is initialized with a constant expression.  

How To Find Current / System / Today's Date/Time/Both In Java 8

    Finding Today’s date in Java is sometimes necessary. For example, while creating excel reports, you may need to fill the current date in any column. The java.time package in java 8 has 3 classes for this purpose, those are  java.time.LocalDate  java.time.LocalTime  java.time.LocalDateTime All these 3 classes are final classes, you have to call one of their factory methods to get an instance. All the 3 classes have method now(), which gives an instance of the particular class. java.time.LocalDate : LocalDate is a  A date without a time-zone such as 2007-12-03. It’s an immutable object that represents date in the format “Year - Month - Day” . Getting Current Date In the format “YYYY-MM-DD” : In some cases, you only need current date without time information, in such cases use LocalDate class and call toString() method s on it’s object, i.e LocalDate.now().toString() . Here is the code. import java.time.LocalDate; import java.time...

Date And Time In Java 8 Introduction - The Last Date In Java 6,7,8 Calendar is "Sun Aug 17 12:42:55 IST 292278994"

     Java 8 introduced a new, consistent, and well thought out package for date and time handling. Developers suffered for a decade and half under the inconsistencies and ambiguities of the Date class from Java 1.0 and its replacement, the Calendar class from Java 1.1 . The key benefits of the new API are 1. It provides useful operations such as adding / subtracting dates / times. 2. All the objects are immutable, and thus thread safe. All the new Date and Time classes developed in Java 8, represents time in either continuous or human time. What Is Continuous Time ?     continuous time is based on Unix time i.e the Unix time starts from “January 1, 1970 UTC - 00:00:00”, this is the time Unix was invented. In Unix time system, the unit of increment is one second of time. This has been used as a time base in most operating systems developed since. The time since 1970 is represented as 32 bit integer, and it runs out fairly soon - in the year ...

Joining Strings With Delimiter Using StringJoiner Class In Java 8

     In any programming languages, and in many applications, developers have to put list of values. Frequently these are comma ( “,” ) seperated values, but they can also incorporate other string separators. Java 8 added a new class StringJoiner which is used for this purpose. String Joiner class is added in Java8 under util package. Using String Joiner class, you can join any number of strings with a specified delimiter and starting with a supplied prefix string and ending with a supplied suffix. The StringJoiner class has two parameterized constructors. 1. StringJoiner(CharSequence delimiter) 2. StringJoiner(CharSequence delimiter, CharSequence prefix, CharSequence suffix) Let’s see a simple example, where Strings joining is required. If you run the below code, you will get the output as [java 6, java 7, java 8, java 9] . Here the delimiter is ",", and prefix is "[", and suffix is "]" . package com.speakingcs.practice; import java.util.Arra...

Optional Type, An Alternative To Null In Java 8

     Optional type is an alternative to null. null is used to represent the absense of a value. The biggest problem with null is NullPointerException which raises when you refer to a variable that is null. As a result, frequent checks for a null value were necessary to avoid generating an exception. The Optional Type provide a better way to handle such situations.  Tony Hoare, who invented the concept of null, described it as a " billion dollar mistake". An object of type Optional can either contain a value of type T or be empty. In other words, an Optional object does not necessarily contain a value. Optional doesn't define any constructors. Creating Optional Values : There are several static method for creating Optional values. for example, Optional.of(value) or Optional.empty() are some of them. creating Optional From Value : Optional<String> a = Optional.of("a"); The argument to the method of(T a) must not be null. creating an emp...

External Iteration and Internal Iteration In Java

External Iteration :     While working with Collections, you might have gotten a situation, where you want to iterate over a collection and perform some operation on each element. For example, if we have a list of strings, and we want to count the number of Strings whose length is greater than 5. We would write the code as like below. List strList = Arrays.asList("www","speakingcs","com","posts","java 8"); int count = 0; for(String str : strList) { if(str.length > 5) { count++; } } If you observe the above approach, you can find several problems associated with it. 1. It involves a lot of boilerplate code that needs to written every time you want to iterate over the collection. 2. It's difficult to write a parallel version of this for loop. 3. This code doesn't fluently convey the intent of the programmer. To understand this we must read entire body of the for loop. This becomes burde...

Streams In Java 8

What Is Stream ? Stream is like a pipeline for data. Streams can be sequential or parallel. The parallel streams are designed to take advantage of the multicore hardware design. Streams allow you to write collections processing code at a higher level of abstraction. The Stream API in Java8 uses some of the Java's most advanced features. To fully utilize and understand streams, requires a solid understanding of Generics and Lambda expressions, and also basic concepts of parallelism and working knowledge of the collection framework is needed.  A Stream operates on a data source, such as an array or a collection. Streams allow a collection to send its values out one at a time, through pipeline like mechanism, where they can be processed in various ways with varying degree of parallelism. In Java 8, Stream is a Generic Interface in java.util.stream package. Creating A Stream : Streams are of 2 types, 1. Sequential Streams 2. Parallel Streams In Java 8, 2 defau...

Constructor References In Java 8

Constructor References :     Simillar to Method References, you can create references to the constructors. The only difference is in Constructor references the method name is "new". syntax is : ClassName :: new You may get a doubt that, if the class has multiple constructors which constructor the compiler refers ? The solution is simple , based on the context, the compiler refers the appropriate constructor.  For example if you want to create a string from character array, the compilere referes the string constructor which takes character arry as argument. You can assign a constructor reference to any functional interface which has a mtehod compatible with the constructor. Lets see a simple example. In this example, i am going to refer a Constructor from String class. 1. Define a functional interface. package com.speakingcs.fis; public interface FuncIf {     String strFunc(char[] chArray); } 2. Now assign a String cons...

Method References In JAVA 8

Method References :     Method reference is an important feature related to lambda expressions. It provides a way to a method without executing it. In order to that a method reference requires a target type context that consists of a compatible functional interface. Similar to lambda expressions, a method reference when evaluated creates an instance of the functional interface. The 3 types of method references are, 1. Static Method References. 2. Instance Method References Of Objects. 3. Instance Method References Of Classes. In the first two types, the method reference is equivalent to a lambda expression on which parameters of a method will be supplied. In the 3rd type, the 1st parameter of a method becomes the target of the method and second parameter becomes argument to the method just like s1.equals(s2); . Static Method References :  The syntax for static method references is ClassName :: methodName Lets see a simple example to understand st...

Lambda Expressions part2 : Throwing Exceptions And Capturing Effective Variables

Throwing Exceptions :     First we will start by examining a simple Lambda Expression for creating a Thread. Runnable r = () -> { System.out.println("Thread is going to sleep"); Thread.sleep(1000); } Guess, what is the result of this lambda expressions. It throws a compile time error. Calling sleep() on thread throws Interrupted Exception. We have two options to fix this issue. 1. Catching the exception by enclosing the statement "Thread.sleep(1000) " inside a try / catch block. Just like below. try { Thread.sleep(1000); }catch(InterruptedException ie) { ie.printStackTrace(); }  2. Assigning this lambda expression to a functional interface, whose abstract method can throw the exception. Unfortunately the run() cannot throw any exception. Note that, the prerequisite for a lambda expression to throw a checked exception is that it must be compatible with the exceptions provided after the throws clause of method declaration in the ...

In Detail : Lambda Expressions In JAVA 8 - part 1

Image
What Is A Lambda Expression ? A Lambda Expression is an anonymous method, which is a compact way of passing around behavior as if it were data. The code written using anonymous inner classes serves as data. These classes were designed to make it easier for Java programmers to pass around code as data. Lambda Expressions are used to implement a method specified by a Functional Interface. Visit my previous post on Functional Interfaces from here , for video tutorial you can find here . Thus a Lambda Expression results in a form of anonymous class. There are also commonly referred as closures. Writing The First Lambda Expression :  As i have specified in my previous post on Functional Interfaces, Runnable is a Functional Interface in Java8. So before going to write our first lambda expression, lets see how to create a thread using anonymous inner classes. public class AnonymousThread { public static void main(String[] args) { new Thread(new Runnable() { ...

Functional Interfaces In JAVA8

What is Functional Interface ?     Functional Interface is an Interface which specifies only one abstract method. Functional Interface is a new concept that is introduced in Java 8 as part of Project Lambda. If you have worked with Interfaces in Java previous versions, you might think all the methods declared in Interface are public and abstract implicitly. Although this was true prior to JDK 8, but beginning with JDK 8 it is also possible to specify default behavior for a method declared in Functional Interface. This is called default method. All the non default methods in Functional Interface are implicitly abstract and you don't need to specify modifier " abstract " before the method name.  The existing Interfaces such as Runnable, ActionListener are Functional Interfaces in Java8. Functional Interfaces are also considered as Type for Lambda Expressions. They are sometimes referred to as SAM types, where SAM stands for Single Abstract Method. H...