Home Java javaTutorial Interpret the new features of Java8--the role of lambda

Interpret the new features of Java8--the role of lambda

Jun 17, 2017 pm 02:11 PM
java8 effect characteristic Interpretation

We have been looking forward to lambda bringing the concept of closure to Java for a long time, but if we do not use it in collections, we will lose a lot of value. The problem of migrating existing interfaces to lambda style has been solved through default methods. In this article, we will deeply analyze the batch data operations in Java collections and unravel the mystery of lambda's strongest effect.

We have been waiting for a long time for lambda to bring the concept of closure to Java, but if we do not use it in collections, we will lose a lot of value. The problem of migrating existing interfaces to lambda style has been solved through default methods. In this article, we will deeply analyze the bulk data operation in Java collections and unravel the mystery of the most powerful role of lambda.

1. About JSR335

JSR is the abbreviation of Java Specification Requests, which means Java specification request, the main version of Java 8 An improvement is Project Lambda (JSR 335), which aims to make Java easier to code for multi-core processors.

2. External VS internal iteration

#In the past, Java collections were not able to express internal iteration, but only provided An external iteration method is provided, that is, for or while loop.


List persons = asList(new Person("Joe"), new Person("Jim"), new Person("John"));
for (Person p : persons) {
 p.setLastName("Doe");
}
Copy after login

The above example is our previous approach, which is the so-called external iteration. The loop is a fixed sequence loop. In today's multi-core era, if we want to loop in parallel, we have to modify the above code. How much the efficiency can be improved is still uncertain, and it will bring certain risks (thread safety issues, etc.).

To describe internal iteration, we need to use a class library like Lambda. Let’s use lambda and Collection.forEachRewrite the above loop


persons.forEach(p->p.setLastName("Doe"));
Copy after login

Now the jdk library controls the loop. We don’t need to care about how the last name is set to each person object. The library can decide what to do based on the running environment. Parallel, out-of-order or lazy loading methods. This is internal iteration, and the client passes the behavior p.setLastName as data into the api. In fact, internal iteration is not closely related to batch operations of collections. With its help, we can feel the changes in grammatical expression. The really interesting thing related to batch operations is the new stream API. The new java.util.stream package has been added to JDK 8.

3.Stream API

Stream only represents the data stream and has no data structure, so it has been traversed It can no longer be traversed after one time (you need to pay attention to this when programming, unlike Collection, there is still data in it no matter how many times it is traversed). Its source can be Collection, array, io, etc.

3.1 Intermediate and end-point methods

The function of the stream is to provide an interface for operating big data, allowing data operations Easier and faster. It has methods such as filtering, mapping, and reducing the number of traversals. These methods are divided into two types: intermediate methods and terminal methods. The "stream" abstraction should be continuous by nature. Intermediate methods always return a Stream, so if we want to get the final result If so, an endpoint operation must be used to collect the final result produced by the stream. The difference between these two methods is to look at its return value. If it is a Stream, it is an intermediate method, otherwise it is an end method.

Briefly introduce several intermediate methods (filter, map) and end-point methods (collect, sum)

3.1.1Filter

Implementing the filtering function in the data stream is the most natural operation we can think of first. The Stream interface exposes a filter method, which can accept a Predicate implementation representing an operation to use a lambdaexpression that defines filter conditions.


List persons = …
Stream personsOver18 = persons.stream().filter(p -> p.getAge() > 18);//过滤18岁以上的人
Copy after login

3.1.2Map

Suppose we filter some data now, such as when converting objects. The Map operation allows us to execute an implementation of Function (the generic T and R of Function represent execution input and execution result respectively), which accepts input parameters and returns them. First, let's take a look at how to describe it as an anonymous inner class:


Stream adult= persons
    .stream()
    .filter(p -> p.getAge() > 18)
    .map(new Function() {
     @Override
     public Adult apply(Person person) {
      return new Adult(person);//将大于18岁的人转为成年人
     }
    });
Copy after login

Now, convert the above example into a lambda expression:


Stream map = persons.stream()
     .filter(p -> p.getAge() > 18)
     .map(person -> new Adult(person));
Copy after login

3.1.3Count

The count method is the end point method of a stream, which can make the result of the stream final Statistics, returns int. For example, let’s calculate the total number of people aged 18 or above


int countOfAdult=persons.stream()
      .filter(p -> p.getAge() > 18)
      .map(person -> new Adult(person))
      .count();
Copy after login

3.1.4Collect

collect The method is also the end method of a stream, which can collect the final results


List adultList= persons.stream()
      .filter(p -> p.getAge() > 18)
      .map(person -> new Adult(person))
      .collect(Collectors.toList());
Copy after login

Or, if we want to use a specific implementation class to collect the results:


List adultList = persons
     .stream()
     .filter(p -> p.getAge() > 18)
     .map(person -> new Adult(person))
     .collect(Collectors.toCollection(ArrayList::new));
Copy after login

篇幅有限,其他的中间方法和终点方法就不一一介绍了,看了上面几个例子,大家明白这两种方法的区别即可,后面可根据需求来决定使用。

3.2顺序流与并行流

每个Stream都有两种模式:顺序执行和并行执行。

顺序流:


List <Person> people = list.getStream.collect(Collectors.toList());
Copy after login

并行流:


List <Person> people = list.getStream.parallel().collect(Collectors.toList());
Copy after login

顾名思义,当使用顺序方式去遍历时,每个item读完后再读下一个item。而使用并行去遍历时,数组会被分成多个段,其中每一个都在不同的线程中处理,然后将结果一起输出。

3.2.1并行流原理:


List originalList = someData;
split1 = originalList(0, mid);//将数据分小部分
split2 = originalList(mid,end);
new Runnable(split1.process());//小部分执行操作
new Runnable(split2.process());
List revisedList = split1 + split2;//将结果合并
Copy after login

大家对hadoop有稍微了解就知道,里面的 MapReduce 本身就是用于并行处理大数据集的软件框架,其 处理大数据的核心思想就是大而化小,分配到不同机器去运行map,最终通过reduce将所有机器的结果结合起来得到一个最终结果,与MapReduce不同,Stream则是利用多核技术可将大数据通过多核并行处理,而MapReduce则可以分布式的。

3.2.2顺序与并行性能测试对比

如果是多核机器,理论上并行流则会比顺序流快上一倍,下面是测试代码


long t0 = System.nanoTime();

  //初始化一个范围100万整数流,求能被2整除的数字,toArray()是终点方法

  int a[]=IntStream.range(0, 1_000_000).filter(p -> p % 2==0).toArray();

  long t1 = System.nanoTime();

  //和上面功能一样,这里是用并行流来计算

  int b[]=IntStream.range(0, 1_000_000).parallel().filter(p -> p % 2==0).toArray();

  long t2 = System.nanoTime();

  //我本机的结果是serial: 0.06s, parallel 0.02s,证明并行流确实比顺序流快

  System.out.printf("serial: %.2fs, parallel %.2fs%n", (t1 - t0) * 1e-9, (t2 - t1) * 1e-9);
Copy after login

3.3关于Folk/Join框架

应用硬件的并行性在java 7就有了,那就是 java.util.concurrent 包的新增功能之一是一个 fork-join 风格的并行分解框架,同样也很强大高效,有兴趣的同学去研究,这里不详谈了,相比Stream.parallel()这种方式,我更倾向于后者。

4.总结

如果没有lambda,Stream用起来相当别扭,他会产生大量的匿名内部类,比如上面的3.1.2map例子,如果没有default method,集合框架更改势必会引起大量的改动,所以lambda+default method使得jdk库更加强大,以及灵活,Stream以及集合框架的改进便是最好的证明。

The above is the detailed content of Interpret the new features of Java8--the role of lambda. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Analysis of the function and principle of nohup Analysis of the function and principle of nohup Mar 25, 2024 pm 03:24 PM

Analysis of the role and principle of nohup In Unix and Unix-like operating systems, nohup is a commonly used command that is used to run commands in the background. Even if the user exits the current session or closes the terminal window, the command can still continue to be executed. In this article, we will analyze the function and principle of the nohup command in detail. 1. The role of nohup: Running commands in the background: Through the nohup command, we can let long-running commands continue to execute in the background without being affected by the user exiting the terminal session. This needs to be run

How to display file suffix under Win11 system? Detailed interpretation How to display file suffix under Win11 system? Detailed interpretation Mar 09, 2024 am 08:24 AM

How to display file suffix under Win11 system? Detailed explanation: In the Windows 11 operating system, the file suffix refers to the dot after the file name and the characters after it, which is used to indicate the type of file. By default, the Windows 11 system hides the suffix of the file, so that you can only see the name of the file in the file explorer but cannot intuitively understand the file type. However, for some users, displaying file suffixes is necessary because it helps them better identify file types and perform related operations.

Understand the role and usage of Linux DTS Understand the role and usage of Linux DTS Mar 01, 2024 am 10:42 AM

Understand the role and usage of LinuxDTS In the development of embedded Linux systems, Device Tree (DeviceTree, DTS for short) is a data structure that describes hardware devices and their connection relationships and attributes in the system. The device tree enables the Linux kernel to run flexibly on different hardware platforms without modifying the kernel. In this article, the function and usage of LinuxDTS will be introduced, and specific code examples will be provided to help readers better understand. 1. The role of device tree device tree

Explore the importance and role of define function in PHP Explore the importance and role of define function in PHP Mar 19, 2024 pm 12:12 PM

The importance and role of the define function in PHP 1. Basic introduction to the define function In PHP, the define function is a key function used to define constants. Constants will not change their values ​​during the running of the program. Constants defined using the define function can be accessed throughout the script and are global. 2. The syntax of define function The basic syntax of define function is as follows: define(&quot;constant name&quot;,&quot;constant value&amp;qu

What is PHP used for? Explore the role and functions of PHP What is PHP used for? Explore the role and functions of PHP Mar 24, 2024 am 11:39 AM

PHP is a server-side scripting language widely used in web development. Its main function is to generate dynamic web content. When combined with HTML, it can create rich and colorful web pages. PHP is powerful. It can perform various database operations, file operations, form processing and other tasks, providing powerful interactivity and functionality for websites. In the following articles, we will further explore the role and functions of PHP, with detailed code examples. First, let’s take a look at a common use of PHP: dynamic web page generation: P

Are there any class-like object-oriented features in Golang? Are there any class-like object-oriented features in Golang? Mar 19, 2024 pm 02:51 PM

There is no concept of a class in the traditional sense in Golang (Go language), but it provides a data type called a structure, through which object-oriented features similar to classes can be achieved. In this article, we'll explain how to use structures to implement object-oriented features and provide concrete code examples. Definition and use of structures First, let's take a look at the definition and use of structures. In Golang, structures can be defined through the type keyword and then used where needed. Structures can contain attributes

What is Linux Bashrc? Detailed interpretation What is Linux Bashrc? Detailed interpretation Mar 20, 2024 pm 09:18 PM

LinuxBashrc is a configuration file in the Linux system, used to set the user's Bash (BourneAgainShell) environment. The Bashrc file stores information such as environment variables and startup scripts required for user login, and can customize the user's Shell environment. In the Linux system, each user has a corresponding Bashrc file, which is located in a hidden folder in the user's home directory. The main functions of the Bashrc file are as follows: setting up the environment

What is Crypto GPT? Why is 3EX's Crypto GPT a new entrance to the currency circle? What is Crypto GPT? Why is 3EX's Crypto GPT a new entrance to the currency circle? Jul 16, 2024 pm 04:51 PM

What is CryptoGPT? Why is 3EX’s CryptoGPT said to be a new entrance to the currency circle? According to news on July 5, 3EXAI trading platform officially launched CryptoGPT, an innovative project based on AI technology and big data, aiming to provide comprehensive and intelligent information query and AI investment advice to global crypto investors. CryptoGPT has included the top 200 coins in CoinMarketCap and hundreds of high-quality project party information, and plans to continue to expand. Through CryptoGPT, users can obtain detailed transaction consulting reports and AI investment advice for free, realizing a full-stack closed loop from information consulting services to intelligent strategy creation and automatic execution of transactions. Currently, the service is free. Needed

See all articles