简要介绍JAVA8中的函数式编程;Brief Introduction to Functional Programming in Java 8

转载 2016年03月06日 12:11:11

Brief Introduction to Functional Programming in Java 8

Klaus7828 Feb 2016 CPOL
In this tip, we explain the basics of functional programming in Java 8.

Introduction

Recently, I had the chance to do some work with Java 8. Since until then, I had experience with Java until version 7,  I had to learn some new concepts. In this tip, I would like to describe what I have learned in Java 8 and share it with you.

In Java 8, some elements of functional programming were added to the language. The main purpose for that is  to better support multicore programming.

Multicore programming is a very current topic. Nowadays, the increase of power computation is mainly achieved by increasing the number of CPUs on a single board. The increase of CPU clock frequency was common in the past and continued until the early 2000s, when it stopped because of technological limitations.

Functional programming is a programming paradigm that is particularly suited for multicore programming. Functional programming is based on evaluating functions. Examples of functions are x==2 or x+3, where x is an input parameter. When x is 2 then x+3 evaluates 5.

It is very important to point out that these functions do not modify the input parameters nor variables. In other words, these functions do not change the variables of a program. As a result, these functions can be easily parallelized since there is no risk that function1 and function2 will modify variable1 at the same time. This is a core concept of functional programming.

Java 8 is an object oriented language with support for functional programming. Functional programming in Java 8 involves working with objects, methods but also with functions.

The functions used in Java 8 are special kind of functions called lambda expressions.

Lambda Expressions

A Lambda expression is essentially a function without name and is represented as follows:

(params) -> function body

A Lambda expression consists of three parts:

  1. List of parameters (left of arrow)
  2. Arrow
  3. Function body

Some examples of Lambda expressions are:

(1)      (2)     (3)
x         ->    x + 2

(1)       (2)        (3)
(y,z)     ->     y * z * 2

Lambda expressions can be used in general when you want to pass a piece of code as parameter.

Although the main purpose of functional programming in Java 8 is to simplify the multicore programming, any type of program can benefit from using lambda expressions.

In Java 8, there are two main uses for lambda expressions:

  1. Use lambda expressions instead of anonymous classes
  2. Write operations on collections that can be easily parallelized

Use of Lambda Expressions Instead of Anonymous Classes

You can replace any anonymous class with a lambda expression when the anonymous class has just one method. Anonymous classes are also an attempt to pass a piece of code as parameter.

For example, you can pass a piece of code to be executed to a button when it is clicked in two ways, with anonymous classes and with lambda expressions:

// button click with anonymous classes
button.addActionListener(
      new ActionListener() {
          public void actionPerformed(ActionEvent event) {
          System.out.println("button clicked");
      }
});

// button click with lambda expression
button.addActionListener(event -> System.out.println("button clicked"));

The code with Lambda expression is much more compact.

Use Lambda Expressions to Write Operations on Collections That Can Be Easily Parallelized

Lambda expression can be used on collections by the Stream API.

The Stream API is a new interface introduced in Java 8 that makes it possible to write functional code on collections with lambda expressions. You can think of the Stream as a disguised iterator that allows you to examine all the elements of the collection.

Let's see an example: given a collection of Integers, you want to find the number of values larger than 5.

Without Lambda expressions and Stream API, you would write a piece of code such as:

// code before Java 8
int counter = 0;
for (int val : myIntList) {
    if(val > 5)
        counter++;
}

The code with lambda expressions looks like:

// functional approach with stream and Lambda expressions
int counter = myIntList.stream().filter(n -> n>5).count();

With the stream API, you can call the filter method and pass that lambda expression. You can read the code as follows "give me all values from the collection that satisfy the condition n>5 and count them".

The code with lambda expression has a functional flavor because you pass the Lambda expression n-> n>5 as parameter to the filter function.

Notice that with the lambda expressions, you focus more on what result you want (all values > 5) and not how you get it (this is a matter of the compiler).

When a stream function returns another stream, you can create chains of stream oerations. In the examplestream() and filter() return a stream, so they can be followed by another operation. By contrast, count()returns an int so it cannot be followed by another stream operation.

If you want to parallelize the code on the collection, you can just replace stream with parallelStream.

<code>
int counter1 = myIntList.parallelStream().filter(n -> n>5).count();
</code>

When to use stream or parallelStream is not a trivial task and beyond the purposes of this tip. Among other things, this will depend on the size of the collection, the number of the available CPUs. In the end, you will need to make comparative tests.


http://www.codeproject.com/Tips/1069832/Brief-Introduction-to-Functional-Programming-in-Ja

关于Java8函数式编程你需要了解的几点

函数式编程与面向对象的设计方法在思路和手段上都各有千秋,在这里,我将简要介绍一下函数式编程与面向对象相比的一些特点和差异。...
  • xinaij
  • xinaij
  • 2016年03月31日 22:52
  • 1033

JAVA8新特性 函数式编程Lambda

函数式编程:以处理数据的方式处理代码,这意味着函数可以被赋值给变量,传递给函数等,函数应该是第一等级的值。 纯函数:对于给定的输入总会返回相同的输出,并且不会产生影响或者改变任何的程序状态 http:...
  • crazywaster
  • crazywaster
  • 2016年08月30日 13:17
  • 2284

Java8 Lambda表达式 函数式编程

什么是λ表达式 λ表达式本质上是一个匿名方法。让我们来看下面这个例子:public int add(int x, int y) { return x + y; } 转成λ表达式后是这个样子:(...
  • hnulwt
  • hnulwt
  • 2015年03月17日 10:41
  • 4130

Why Functional Programming Matters 函数式程序设计为什么至关重要

作者: John Hughes 原文地址:http://www.md.chalmers.se/~rjmh/Papers/whyfp.html 此论文作于1984年,作为查麦兹大学的备忘录流传了多...
  • whf727
  • whf727
  • 2014年12月15日 10:50
  • 1421

《java8函数式编程》——流

《java8函数式编程》
  • qq_20278449
  • qq_20278449
  • 2015年10月30日 10:47
  • 1315

Java8:函数接口(Functional interfaces)

Java8:λ表达式是匿名类的语法糖 的补充资料。 1.定义 一个函数接口 (Functional interfaces,早期它们被称为SAM(单一抽象方法/Single Abstract Met...
  • yqj2065
  • yqj2065
  • 2016年06月07日 18:36
  • 791

《java8函数式编程》——使用函数式编程重构代码

遗留代码:找出长度大于1分钟的歌曲 public Set findLongTracks(List albums){ Set tracksNames=new HashSet(); for...
  • qq_20278449
  • qq_20278449
  • 2015年10月30日 16:10
  • 850

java 8功能性接口(Functional)

Ø  JDK1.8包括了许多功能性接口。它们中的一些是老版本中被熟知的接口,例如Comparator和Runnable。这些已存在的接口已经通过@FunctionalInterface注解扩展为支持L...
  • u011659172
  • u011659172
  • 2016年09月19日 11:34
  • 920

java8 lambda 使用 与 functional interface 与 function 类

java 8 中的 function 类 属于 lamda表达式的一种,它定义好了一些借口,可以直接来调用,比较方便。 举例: import java.util.function.Function...
  • robert_chen1988
  • robert_chen1988
  • 2017年07月08日 00:56
  • 493

java8新增特性(二)----函数式接口(Functional)

上一篇博客介绍了java8新增的Lambda表达式,这一节介绍一下java8的函数式编程,两者之间有什么联系呢?请往下看~~~      Lambda表达式如何在java类型中表示的呢?  ...
  • liu136313
  • liu136313
  • 2015年08月22日 15:40
  • 1946
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:简要介绍JAVA8中的函数式编程;Brief Introduction to Functional Programming in Java 8
举报原因:
原因补充:

(最多只允许输入30个字)