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

Brief Introduction to Functional Programming in Java 8

Klaus7828 Feb 2016  CPOL
Rate this:  
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

深度学习是机器学习的一个子领域,它基于人工神经网络的研究,特别是利用多层次的神经网络来进行学习和模式识别。深度学习模型能够学习数据的高层次特征,这些特征对于图像和语音识别、自然语言处理、医学图像分析等应用至关重要。以下是深度学习的一些关键概念和组成部分: 1. **神经网络(Neural Networks)**:深度学习的基础是人工神经网络,它是由多个层组成的网络结构,包括输入层、隐藏层和输出层。每个层由多个神经元组成,神经元之间通过权重连接。 2. **前馈神经网络(Feedforward Neural Networks)**:这是最常见的神经网络类型,信息从输入层流向隐藏层,最终到达输出层。 3. **卷积神经网络(Convolutional Neural Networks, CNNs)**:这种网络特别适合处理具有网格结构的数据,如图像。它们使用卷积层来提取图像的特征。 4. **循环神经网络(Recurrent Neural Networks, RNNs)**:这种网络能够处理序列数据,如时间序列或自然语言,因为它们具有记忆功能,能够捕捉数据的时间依赖性。 5. **长短期记忆网络(Long Short-Term Memory, LSTM)**:LSTM 是一种特殊的 RNN,它能够学习长期依赖关系,非常适合复杂的序列预测任务。 6. **生成对抗网络(Generative Adversarial Networks, GANs)**:由两个网络组成,一个生成器和一个判别器,它们相互竞争,生成器生成数据,判别器评估数据的真实性。 7. **深度学习框架**:如 TensorFlow、Keras、PyTorch 等,这些框架提供了构建、训练和部署深度学习模型的工具和库。 8. **激活函数(Activation Functions)**:如 ReLU、Sigmoid、Tanh 等,它们在神经网络用于添加非线性,使得网络能够学习复杂的函数。 9. **损失函数(Loss Functions)**:用于评估模型的预测与真实值之间的差异,常见的损失函数包括均方误差(MSE)、交叉熵(Cross-Entropy)等。 10. **优化算法(Optimization Algorithms)**:如梯度下降(Gradient Descent)、随机梯度下降(SGD)、Adam 等,用于更新网络权重,以最小化损失函数。 11. **正则化(Regularization)**:技术如 Dropout、L1/L2 正则化等,用于防止模型过拟合。 12. **迁移学习(Transfer Learning)**:利用在一个任务上训练好的模型来提高另一个相关任务的性能。 深度学习在许多领域都取得了显著的成就,但它也面临着一些挑战,如对大量数据的依赖、模型的解释性差、计算资源消耗大等。研究人员正在不断探索新的方法来解决这些问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值