Java Lambda Expression Archives - Huong Dan Java https://huongdanjava.com/tag/java-lambda-expression-en Java development tutorials Fri, 25 Jan 2019 05:44:35 +0000 en-US hourly 1 https://wordpress.org/?v=6.9.4 https://huongdanjava.com/wp-content/uploads/2018/01/favicon.png Java Lambda Expression Archives - Huong Dan Java https://huongdanjava.com/tag/java-lambda-expression-en 32 32 Constructor reference in Java https://huongdanjava.com/constructor-reference-in-java.html https://huongdanjava.com/constructor-reference-in-java.html#respond Tue, 11 Dec 2018 19:07:10 +0000 https://huongdanjava.com/?p=12603 I have introduced the method reference in the previous tutorial, in this tutorial, I introduce you another new concept: constructor reference. Like the method reference, the constructor reference is used to abbreviate the Lambda Expression expression. How is it in details? Suppose you are working… Read More

The post Constructor reference in Java appeared first on Huong Dan Java.

]]>
I have introduced the method reference in the previous tutorial, in this tutorial, I introduce you another new concept: constructor reference. Like the method reference, the constructor reference is used to abbreviate the Lambda Expression expression. How is it in details?

Suppose you are working with a Lambda Expression like this:

(args) -> new ClassName(args)

In this expression Lambda Expression, the body part we have only a code for initializing a new object with the constructor having or not having argument parameters.

To be concise, we can use the constructor reference as follows:

ClassName::new

For the example of this constructor reference, I will use some of the interfaces in the java.util.function package.

With the constructor without parameters, we will use the Supplier interface with the Lambda Expression expression as follows:

Supplier<List<String>> s = () -> new ArrayList<>();

Rewrite with the constructor reference:

Supplier<List<String>> s = ArrayList::new;

Given a constructor with a parameter, we will use the Function interface with the Lambda Expression expression as follows:

Function<String, Integer> f = s -> new Integer(s);

Rewrite with the constructor reference:

Function<String, Integer> f = Integer::new;

The post Constructor reference in Java appeared first on Huong Dan Java.

]]>
https://huongdanjava.com/constructor-reference-in-java.html/feed 0
Functional Interface in Java https://huongdanjava.com/functional-interface-in-java.html https://huongdanjava.com/functional-interface-in-java.html#respond Tue, 11 Dec 2018 17:51:03 +0000 https://huongdanjava.com/?p=12583 In the Lambda Expression tutorials, I introduced you to the Functional Interface and its importance when using Lambda Expression in Java code. In this tutorial, I will talk more about Functional Interface! Definition of Functional Interface OK, let me first talk about the definition of… Read More

The post Functional Interface in Java appeared first on Huong Dan Java.

]]>
In the Lambda Expression tutorials, I introduced you to the Functional Interface and its importance when using Lambda Expression in Java code. In this tutorial, I will talk more about Functional Interface!

Definition of Functional Interface

OK, let me first talk about the definition of Functional Interface in the most complete and detailed way.

First of all, surely, the functional interface must be an interface.
For example:

package com.huongdanjava;

public interface SayHello {
}

The second is that it has only one and only one abstract method. Lambda Expression will implement this abstract method.
For example, the following interface’s say() method is an abstract method:

package com.huongdanjava;

public interface SayHello {
	void say(String name);
}

The third one is not mandatory, but you should know: we can use the @FunctionalInterface annotation to mark the class we want as a Functional Interface.
For example:

package com.huongdanjava;

@FunctionalInterface
public interface SayHello {
	void say();
}

After an interface is marked with the annotation above, you cannot add another abstract method. If you try then a compile error will occur immediately.

Functional Interface in Java


Some Functional Interfaces in Java

From Java 7 and earlier, we have some interfaces that can be considered as Functional Interfaces from Java 8 onwards, such as:

FileFilter with only one abstract method:

boolean accept(File pathname);

ActionListener also has an abstract method:

public void actionPerformed(ActionEvent e);

From Java 8 onwards, Java provides us with more functionalities. They are defined in the java.util.function package:

Functional Interface in Java

You can find out more about them here.

The post Functional Interface in Java appeared first on Huong Dan Java.

]]>
https://huongdanjava.com/functional-interface-in-java.html/feed 0
Type Inference in Java https://huongdanjava.com/type-inference-in-java.html https://huongdanjava.com/type-inference-in-java.html#respond Mon, 23 Apr 2018 22:46:13 +0000 https://huongdanjava.com/?p=8517 Type Inference in Java is a Java Compiler’s ability base on the declaration, the calling to determine the datatype, without explicitly declaring it, reducing redundancy code. For you to understand more, I will take an example as follows. Assuming you are working with the List… Read More

The post Type Inference in Java appeared first on Huong Dan Java.

]]>
Type Inference in Java is a Java Compiler’s ability base on the declaration, the calling to determine the datatype, without explicitly declaring it, reducing redundancy code.

For you to understand more, I will take an example as follows.

Assuming you are working with the List object, we usually initialize it as follows:

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

As you can see, we have to declare the same data type on the left and right of the above expression. Why do we have to repeat it twice? Why not declare once and the rest to let Java Compiler self-understand?

This is what causes Type Inference to be introduced. With Type Inference, we write the following:

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

You see, using Type Inference we can eliminate a “<String>”.

To apply Type Inference to the above example, you simply replace the right datatype with Diamond character (“<>”).

The second example is the Lambda Expression.

Suppose you have an interface like this:

package com.huongdanjava.javaexample;

public interface Calculator {

	int add(int a, int b);
}

Now, I will use this interface in my application with Lambda Expression as follows:

package com.huongdanjava.javaexample;

public class Example {

	public static void main(String[] args) {
		Calculator calculator = (a, b) -> a + b;
		System.out.println(calculator.add(2, 3));
	}
}

Result:

Type Inference in Java

Obviously, as you can see, although we do not use the return statement in the Lambda Expression, the Java Compiler, based on how we declare the interface and method in this interface, automatically understands that there will be a value returned at the end of the body in Lambda Expression.

The post Type Inference in Java appeared first on Huong Dan Java.

]]>
https://huongdanjava.com/type-inference-in-java.html/feed 0
Data type of Lambda Expression in Java https://huongdanjava.com/data-type-lambda-expression-java.html https://huongdanjava.com/data-type-lambda-expression-java.html#respond Tue, 29 Aug 2017 23:13:09 +0000 https://huongdanjava.com/?p=3952 In Java, we know that two types of data are primitive and object. So, Lambda Expression is defined as an anonymous function, what is its data type? In this tutorial, let’s find out together! OK, as I mentioned earlier, Lambda Expression is used with a… Read More

The post Data type of Lambda Expression in Java appeared first on Huong Dan Java.

]]>
In Java, we know that two types of data are primitive and object. So, Lambda Expression is defined as an anonymous function, what is its data type? In this tutorial, let’s find out together!

OK, as I mentioned earlier, Lambda Expression is used with a Functional Interface. This means, we can use Lambda Expression wherever its data type is a Functional Interface.

Functional Interface basically has only one abstract method, so we can easily map it to a Lambda Expression to implement that abstract method. During compile and runtime, Java generates an object with a Functional Interface data type that uses the content of Lambda Expression implementation.

But it is important to remember that there is no class and therefore no object is directly related to this Lambda Expression. It is just an instruction for Java to create an object for the Functional Interface.


The post Data type of Lambda Expression in Java appeared first on Huong Dan Java.

]]>
https://huongdanjava.com/data-type-lambda-expression-java.html/feed 0
Filter a Map using Stream and Lambda Expression in Java https://huongdanjava.com/filter-a-map-using-stream-and-lambda-expression-in-java.html https://huongdanjava.com/filter-a-map-using-stream-and-lambda-expression-in-java.html#respond Thu, 03 Aug 2017 22:12:20 +0000 https://huongdanjava.com/?p=3534 To filter a Map using Stream and Lambda Expression in Java, we will use the filter() method of Stream object which will be retrieved from Entry object of Map object with Lambda Expression as filter a List. How is it in details? Let learn together in… Read More

The post Filter a Map using Stream and Lambda Expression in Java appeared first on Huong Dan Java.

]]>
To filter a Map using Stream and Lambda Expression in Java, we will use the filter() method of Stream object which will be retrieved from Entry object of Map object with Lambda Expression as filter a List. How is it in details? Let learn together in this tutorial.

Example, I have the following Map object as below:

Map<String, Integer> studentMap = new HashMap<>();
studentMap.put("Khanh", 31);
studentMap.put("Thanh", 25);
studentMap.put("Dung", 35);

Before Java 8, to filter this Map and only get the age of Khanh, we can write the code as below:

int age = 0;
for (Map.Entry<String, Integer> entry : studentMap.entrySet()) {
    if ("Khanh".equals(entry.getKey())) {
        age = entry.getValue();
    }
}

Result:

Filter a Map using Stream and Lambda Expression in Java

Since Java 8, we can re-write this code as below:

Integer result = studentMap.entrySet().stream()
    .filter(map -> "Khanh".equals(map.getKey()))
    .map(map -> map.getValue())
    .findFirst()
    .get();

System.out.println(result);

Result:

Filter a Map using Stream and Lambda Expression in JavaHere you can also filter a Map and return a new Map as below:

Map<String, Integer> result = studentMap.entrySet().stream()
    .filter(map -> "Khanh".equals(map.getKey()))
    .collect(Collectors.toMap(m -> m.getKey(), m -> m.getValue()));

System.out.println(result);

Result:

Filter a Map using Stream and Lambda Expression in Java

 

The post Filter a Map using Stream and Lambda Expression in Java appeared first on Huong Dan Java.

]]>
https://huongdanjava.com/filter-a-map-using-stream-and-lambda-expression-in-java.html/feed 0
Introduce about Stream in Java https://huongdanjava.com/introduce-about-stream-in-java.html https://huongdanjava.com/introduce-about-stream-in-java.html#respond Thu, 27 Jul 2017 03:37:04 +0000 https://huongdanjava.com/?p=3409 Stream is a new Java object, was introduced from Java 8. It helps us can manipulate on collections and arrays easier and more efficient. So what is it? In this article, I will introduce with you all about the Stream in Java. First, consider the… Read More

The post Introduce about Stream in Java appeared first on Huong Dan Java.

]]>
Stream is a new Java object, was introduced from Java 8. It helps us can manipulate on collections and arrays easier and more efficient. So what is it? In this article, I will introduce with you all about the Stream in Java.

First, consider the following example:

package com.huongdanjava.example;

import java.util.Arrays;
import java.util.List;

public class Example {

	public static void main(String[] args) {
		List<String> names = Arrays.asList("Khanh", "Thanh", "Dung");

		names.stream()
			.filter(s -> s.startsWith("K"))
			.forEach(System.out::println);
	}
}

In this example, we have a List of the String object. From this List object, we convert it into the object of the Stream, then use this Stream object to filter the String starting with the “K” character, and finally print the String object beginning with “K” to the console.

Result:

Introduce about Stream in Java

Obviously, as you can see, using Stream with Lambda Expression makes our code easier to understand and read.

In the code above, we take the Stream object from the Collection object, would you feel like Stream is a Collection? It’s not, Stream is not a Collection.

Simply, Stream is a collection and array wrapper. It wraps an existing collection and other data sources to support manipulation on that collections or data sources using Lambda Expression. So, you just need specify what you want to do, and how to do it, Stream will worry about that.

Characteristics of Stream include:

  • Stream perfect support for Lambda Expression.
  • Stream does not contain collection or array elements.
  • Stream is an immutable object.
  • The stream is not reusable, meaning that once it is used, we can not call it again for using.
  • We cannot use the index to access elements in the Stream.
  • Stream supports parallel manipulation of elements in a collection or array.
  • Stream supports lazy manipulation, as needed, new operations are performed.

To do this, most operations with Stream return a new Stream, which creates a chain containing a series of operations to perform the operation in the most optimal way. This chain is also called a pipeline.

There are three main steps to create a pipeline for Stream:

Create a new Stream.

The Stream interface in the java.util.stream package is the interface that represents a Stream. This interface only works with the data type is object.

With primitives, you can use Stream objects for those types of primitives, such as IntStream, LongStream, or DoubleStream.

We have many ways to create a new Stream:

Create a new Stream from a collection

Eg:

List<String> names = Arrays.asList("Khanh", "Thanh", "Dung");
Stream<String> stream = names.stream();

Create new Stream from certain values using the Stream interface.

Eg:

Stream<String> stream = Stream.of("Khanh", "Thanh", "Dung");

Create Stream from an array.

Eg:

String[] names = { "Khanh", "Thanh", "Dung" };
Stream<String> stream = Stream.of(names);

Use 0 or more intermediate operations to convert an original Stream into a new one.

Stream has many intermediate operations to manipulate Stream, as shown at the beginning of the article we used:

Stream<String> stream = Stream.of("Khanh", "Thanh", "Dung");
stream.filter(s -> s.startsWith("K")).distinct();

Most intermediate operations return a new Stream object.

The important thing that you all need to know is even though we define many intermediate operations but they do not perform these operations immediately. Only when the terminal operation is called, these intermediates will be performed.

Use of terminal operation to retrieve results or a side-effect from defined intermediate operations.

You can easily to determine what is an intermediate operation, what is a terminal operation because the terminal operation will return a void or non-stream object.

After the terminal operation is called, Stream will no longer be available. If you want to use it again, you must create a new Stream from the collection or array you want.


The post Introduce about Stream in Java appeared first on Huong Dan Java.

]]>
https://huongdanjava.com/introduce-about-stream-in-java.html/feed 0
Convert an object into another type using Lambda Expression and Stream in Java https://huongdanjava.com/convert-an-object-into-another-type-using-lambda-expression-and-stream-in-java.html https://huongdanjava.com/convert-an-object-into-another-type-using-lambda-expression-and-stream-in-java.html#comments Tue, 25 Jul 2017 21:57:11 +0000 https://huongdanjava.com/?p=3396 Since Java 8, we have ability to convert an object into another type by using map() method of Stream object with Lambda Expression. In this tutorial, I will show to you all some examples about it. Note that, map() method is an intermediate operation in… Read More

The post Convert an object into another type using Lambda Expression and Stream in Java appeared first on Huong Dan Java.

]]>
Since Java 8, we have ability to convert an object into another type by using map() method of Stream object with Lambda Expression. In this tutorial, I will show to you all some examples about it.

Note that, map() method is an intermediate operation in Stream, so we need more a terminal method to complete pipeline Stream. You can see more about Stream object here.

The first example, we can convert a List of String in lowercase to a List of String in uppercase using map() method.

Before Java 8, we can do that like below:

List<String> names = new ArrayList<>();
names.add("Thanh");
names.add("Khanh");
names.add("Tan");

List<String> namesUpper = new ArrayList<>();
for (String s : names) {
    namesUpper.add(s.toUpperCase());
}

System.out.println(namesUpper.toString());

Result:

Convert an object into another type using Lambda Expression and Stream in Java

And now, if we rewrite this code using map() method of Stream object with Lambda Expression from Java 8:

List<String> names = new ArrayList<>();
names.add("Thanh");
names.add("Khanh");
names.add("Tan");

List<String> namesUppper = names.stream()
    .map(x -> x.toUpperCase())
    .collect(Collectors.toList());
System.out.println(namesUppper);

The result will be same:

Convert an object into another type using Lambda Expression and Stream in Java


The second example, that is we can extract some information from the object to some other objects with map() method.

Example, I have a Student object like below:

package com.huongdanjava.javaexample;

import java.util.Date;

public class Student {

    private String name;
    private Date dateOfBirth;


    public Student(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Date getDateOfBirth() {
        return dateOfBirth;
    }

    public void setDateOfBirth(Date dateOfBirth) {
        this.dateOfBirth = dateOfBirth;
    }
}

Now, I can extract list of Student object into list of String object of student name as follows.

List<Student> students = Arrays.asList(
    new Student("Khanh"),
    new Student("Thanh"),
    new Student("Tan"));
List<String> names = students.stream()
    .map(s -> s.getName())
    .collect(Collectors.toList());

System.out.println(names);

In this example, s variable present for a Student object and you can get name of all students then put it into a List object.

Result:

Convert an object into another type using Lambda Expression and Stream in Java

 

The post Convert an object into another type using Lambda Expression and Stream in Java appeared first on Huong Dan Java.

]]>
https://huongdanjava.com/convert-an-object-into-another-type-using-lambda-expression-and-stream-in-java.html/feed 2
Filter a List using Lambda Expression and Stream in Java https://huongdanjava.com/filter-a-list-using-lambda-expression-and-stream-in-java.html https://huongdanjava.com/filter-a-list-using-lambda-expression-and-stream-in-java.html#respond Fri, 21 Jul 2017 22:16:23 +0000 https://huongdanjava.com/?p=3321 Normally, before Java 8, when we want to filter a List, we will iterate through the List and base on the condition we want to filter, we can have a new List on demand. For example, I have a List containing some student names as… Read More

The post Filter a List using Lambda Expression and Stream in Java appeared first on Huong Dan Java.

]]>
Normally, before Java 8, when we want to filter a List, we will iterate through the List and base on the condition we want to filter, we can have a new List on demand.

For example, I have a List containing some student names as below:

List<String> names = new ArrayList<>();
names.add("Thanh");
names.add("Khanh");
names.add("Tan");

Now, I want to filter above List to have a new List containing the student names only start with the letter “T”, then I will code as below:

List<String> namesStartWithT = new ArrayList<>();
for (String s : names) {
    if (s.startsWith("T")) {
        namesStartWithT.add(s);
    }
}

System.out.println(namesStartWithT);

Result:

Filter a List using Lambda Expression and Stream in Java

Since Java 8, we have another better way to do this by using Stream and Lambda Expression. Detail is: we will create new Stream object from our List object and use filter() method in this Stream object to filter.

Stream stream = names.stream().filter(s -> s.startsWith("T"));

The argument of filter() method is Predicate interface, a Functional interface, and this method is an intermediate operation. Then we need to add more method for a terminal operation to complete a Stream pipeline.

Here, after filtering, I will collect all the result into a List object by using terminal method collect() of Stream as below:

List list = names.stream()
    .filter(s -> s.startsWith("T"))
    .collect(Collectors.toList());

System.out.println(list.toString());

When running the code, the result will be same as above.

Filter a List using Lambda Expression and Stream in Java

 

The post Filter a List using Lambda Expression and Stream in Java appeared first on Huong Dan Java.

]]>
https://huongdanjava.com/filter-a-list-using-lambda-expression-and-stream-in-java.html/feed 0
Using Lambda Expression to sort a List in Java https://huongdanjava.com/using-lambda-expression-to-sort-a-list-in-java.html https://huongdanjava.com/using-lambda-expression-to-sort-a-list-in-java.html#respond Thu, 20 Jul 2017 22:47:10 +0000 https://huongdanjava.com/?p=3284 Normally, before Java 8, when we want to sort a List object, we will use Comparator object. For example: [crayon-69b8b9ac2c8f4942225014/] Result: Since Java 8, we have another way to do the sorting a List object. That is: using sort() method in List object with Lambda… Read More

The post Using Lambda Expression to sort a List in Java appeared first on Huong Dan Java.

]]>
Normally, before Java 8, when we want to sort a List object, we will use Comparator object.

For example:

package com.huongdanjava.javaexample;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class Example {

	public static void main(String[] args) {
		List<String> names = new ArrayList<>();
		names.add("Thanh");
		names.add("Khanh");
		names.add("Tan");

		Collections.sort(names, new Comparator<String>() {
		    @Override
		    public int compare(String s1, String s2) {
		        return s1.compareTo(s2);
		    }
		});

		for (String s : names) {
			System.out.println(s);
		}
	}
}

Result:

Using Lambda Expression to sort a List in Java

Since Java 8, we have another way to do the sorting a List object. That is: using sort() method in List object with Lambda Expression.

Back to my example, I can re-write the code using sort() method and Lambda Expression as below:

package com.huongdanjava.javaexample;

import java.util.ArrayList;
import java.util.List;

public class Example {

	public static void main(String[] args) {
		List<String> names = new ArrayList<>();
		names.add("Thanh");
		names.add("Khanh");
		names.add("Tan");

		names.sort((s1, s2) -> s1.compareTo(s2));

		names.forEach(System.out::println);
	}
}

The argument of sort() method is a Comparator interface and because Comparator interface has just only one method, then we can call it is Functional Interface and apply Lambda Expression for it.

When we run again the example, we will get the same result as above.

Using Lambda Expression to sort a List in Java

 

The post Using Lambda Expression to sort a List in Java appeared first on Huong Dan Java.

]]>
https://huongdanjava.com/using-lambda-expression-to-sort-a-list-in-java.html/feed 0
Using Lambda Expression to foreach a Map object in Java https://huongdanjava.com/using-lambda-expression-to-foreach-a-map-object-in-java.html https://huongdanjava.com/using-lambda-expression-to-foreach-a-map-object-in-java.html#respond Tue, 18 Jul 2017 09:55:22 +0000 https://huongdanjava.com/?p=3286 In this tutorial, I will show you all how using Lambda Expression to foreach a Map object in Java. OK, let’s get started! Same like List object, the forEach () method is also added to the Map object since Java 8, which gives us more… Read More

The post Using Lambda Expression to foreach a Map object in Java appeared first on Huong Dan Java.

]]>
In this tutorial, I will show you all how using Lambda Expression to foreach a Map object in Java.

OK, let’s get started!

Same like List object, the forEach () method is also added to the Map object since Java 8, which gives us more ways to print the elements in this object.
For example, I have a Map object like this:

Map<String, String> students = new HashMap<>();
students.put("name", "Khanh");
students.put("age", "20");
students.put("dateofBirth", "24-06-1997");

Normally, I would write code like this:

for (Map.Entry<String, String> entry : students.entrySet()) {
    System.out.println(entry.getKey() + " : " + entry.getValue());
}

With the forEach() method and Lambda Expression, our code will be as simple as this:

students.forEach((k, v) -> System.out.println(k + " : " + v));

The argument of forEach() method in the Map object is BiConsumer, a Functional Interface.
Result:

dateofBirth : 24-06-1987
name : Khanh
age : 20

The post Using Lambda Expression to foreach a Map object in Java appeared first on Huong Dan Java.

]]>
https://huongdanjava.com/using-lambda-expression-to-foreach-a-map-object-in-java.html/feed 0