Skip to main content

Posts

Showing posts from October, 2020

Method Reference in Java

In the post Lambda expression in Java we have already seen how Lambda expression provides an instance of functional interface and implements the abstract method of the functional interface . Though sometimes, a lambda expression is used just to call an existing method. In those cases you can refer to the existing method by name using Method references in Java . Method reference is a compact and more readable lambda expressions for methods that already have a name. For example consider the following lambda expression- List<Integer> list = Arrays.asList(1, 2, 3, 4, 5); list.forEach((Integer a) -> System.out.println(a)); Here lambda expression is just calling an existing method which can be done using method reference making the code more readable and concise. List<Integer> list = Arrays.asList(1, 2, 3, 4, 5); list.forEach(System.out::println); Table of contents Method reference also needs a target type Java Method reference syntax Kinds of Method Ref

Built-in Functional Interfaces in Java

Post about Functional Interface in Java gives an overview of functional interfaces and how Lambda expressions can be used to implement functional interfaces. At the same time it doesn’t mean whenever you want to use lambda expression you will have to write your own custom functional interface. In Java there are many built-in functional interfaces which cover many different contexts when used with lambda expressions in Java . Table of contents Built-in functional interfaces Java package Consumer functional interface Supplier functional interface Function functional interface Operator functional interfaces Predicate Functional interface Built-in functional interfaces Java package In Java there is a package java.util.function that defines many general purpose functional interfaces used by the JDK and used by user code as well. Functional interfaces in this package can be categorized into five types- Consumer Function Predicate Supp

Functional Interface in Java

Functional interface in Java is an interface with a single abstract method. Here is a functional interface example in Java. interface MyFunctionalInterface{ void calculateInterest(int i); } This interface qualifies as a functional interface because there is a single unimplemented method in the interface. Table of contents What qualifies as a functional interface Functional interface and Lambda expression @FunctionalInterface annotation in Java Pre-packaged Functional interfaces in Java Example using BiFunction functional interface Example using Predicate functional interface What qualifies as a functional interface Java 8 onward an interface can have default methods , static methods and Java 9 onward even private methods , so a functional interface can have these methods too but it should have only a single unimplemented method to be qualified as a functional interface. If an interface declares an abstract method overriding one of the public method

Variable Scope in Java Lambda Expression

In this post we’ll see what is the scope of a variable with in a lambda expression in Java . This topic is important as it touches one of the concept that’s added in Java 8; Effectively final in Java. Java lambda expression variable scope Lambda expression in Java doesn’t have a scope of its own, it has the same scope as its enclosing scope. It results in an error if a variable is defined with in a lambda expression that has the same name as a variable in its enclosing scope. For example- String s1 = "Lambda"; // Error Comparator<String> comp = (s1, s2) -> s1.length() - s2.length(); This lambda expression implements the compare() method of the Comparator functional interface but that will result in an error as the parameter used with in the lambda expression has the same name as the local variable s1 already defined. Thus this statement results in compile time error “ Lambda expression's parameter s1 cannot redeclare another local variable defined in

Exception Handling With Java Lambda Expressions

In this post we’ll see exception handling with lambda expressions in Java. A lambda expression can throw an exception but that should be compatible with the exceptions specified in the throws clauses of the abstract method of the functional interface . If a lambda expression body throws a checked exception , the throws clause of the functional interface method must declare the same exception type or its supertype. Checked exception in lambda expression In the example abstract method calculate of the functional interface MyFunctionalInterface doesn't have a throws clause but lambda body throws an exception. In such case a compiler error message " Unhandled exception type Exception " is generated. If you specify the same exception in the functional interface method then the error is resolved but then you do need to handle it while calling the method. @FunctionalInterface interface MyFunctionalInterface{ int calculate(int i, int j) throws Exception; } publ

Java Lambda Expressions With Examples

Java Lambda expression is one of the most important addition in Java 8. It is a step towards functional programming in Java programming language. This Java Lambda expression tutorial gives an overview of lambda expressions like what are lambda expressions, how to write one and what are the advantages of using lambda expressions. Table of contents Functional interface in Java Lambda expression in Java Arrow operator or Lambda operator Lambda expressions in Java examples Lambda expression as a method argument Block lambda expressions in Java Functional interface in Java Before delving deep into lambda expressions you should know about the functional interfaces in Java. A functional interface is an interface with only a single abstract method (SAM) . There are already many functional interfaces in Java  (though many new ones added in Java 8) like Runnable with its single run() method, Callable with its call() method or Comparator with its compare() me

Generic Bubble Sort Java Program

In this post we’ll see how to write a Bubble Sort program as a Generic class in Java which can be used with arrays of different data types. Bubble Sort- Java Generic class In the generic class used for Bubble Sort we use a bounded parameter to restrict the type to be of type Comparable. That is done as we do need to compare the elements for sorting for which compareTo() method of the Comparable is used. import java.util.Arrays; public class BubbleSortGeneric<T extends Comparable<? super T>> { T[] array; BubbleSortGeneric(T[] array){ this.array = array; } private T[] bubbleSort(){ for(int i = array.length; i > 1; i--){ for(int j = 0; j < i - 1; j++){ //if greater swap elements if(array[j].compareTo(array[j+1]) > 0){ swapElements(j, array); } } } return array; } private void swapElements(int index, T[] arr){ T temp = arr[index]; arr[index] = arr[index+1]; arr[i

Java Generics- Generic Class, Interface And Method

Generics in Java was introduced in Java 5 to provide strict type checking at compile time. Table of contents Type parameters in Java Generics Why Generics is required Benefits of Java Generics Type Parameter Naming Conventions in Java Generics Generic Class Generic Interface Generic Method The Diamond Operator Type parameters in Java Generics Generics in Java enables you to write generic classes, interfaces and methods that can work with different data types. It is possible because you specify type parameters when defining classes, interfaces and methods. Type parameter can be any class or interface like Integer, String, custom class or interface. For example in Collection API ArrayList class is written as- public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable { .. .. } Here E is a type parameter which is enclosed in angle brackets (<>). Since a t

How to Convert float to int in Java

In this post we’ll see how to convert float to int in Java. Considerations while converting float to int in Java While converting float to int two things you need to consider are- Range of float is more than the int, if the float you are trying to convert to int is out of range for int then how to handle that. In float value there are fractional parts where as int doesn’t have fractional part so what to do with fractional part is another thing to consider. Fractional part can be truncated or you need to round it. Converting using intValue() method or by type casting You can convert float to int using intValue() method of the Float class (needs a Float object) or by explicitly type casting float value to int. In fact intValue() method implementation also do the type casting and returns the value of this Float as an int after a narrowing primitive conversion . Problem with these two methods is that the rounding to the nearest integer doesn’t happen while converting f

How to Create Temporary File in Java

Sometimes in your Java application you may want to store some data in a temporary file that can safely be deleted when the work is done. Java IO and NIO APIs itself provide methods to create a temporary file in Java. Table of contents Methods in java.io.File class to create temporary file Temporary file creation Java example using java.io.File class methods Methods in java.nio.file.Files class to create temporary file Temporary file creation Java example using java.nio.file.Files class methods Methods in java.io.File class to create temporary file In java.io.File class there are two methods: createTempFile(String prefix, String suffix) - Creates an empty file in the default temporary-file directory, using the given prefix and suffix to generate its name. createTempFile(String prefix, String suffix, File directory) - Creates a temp file in the specified directory, using the given prefix and suffix strings to generate its name. Specified directory should