Home Java javaTutorial Example explanation of functional programming in Java8

Example explanation of functional programming in Java8

Aug 09, 2017 pm 02:03 PM
java8 Example programming

Functional programming, this word consists of two nouns, function and programming. I don’t need to explain the word programming, everyone does it. Function, in fact, it is not unfamiliar to separate this word. So what is the combination of the two? The following article mainly introduces you to the relevant information about Java8 functional programming. Friends who need it can refer to it. .

Preface

In a previous article we quickly learned lambda and Stream, in this chapter we review and understand functional expressions Programming ideas. We keep mentioning the term functional, does it refer to lambda? If so, what benefits can you get from adopting functional programming?

Thinking Functionally

Imperative Programming

Generally, we have two ways of thinking about implementing a system. One is focused on how to implement it, such as cooking. Usually, you follow the cooking method you are familiar with: first wash the vegetables, then cut the vegetables, Heat the oil, serve, and then... This looks like a series of orders. We call this "how to do" programming style imperative programming. Its characteristics are very similar to the assembly line of a factory and the instruction processing of a computer, both of which are serialized and imperative.


CookingTask cookingTask = new CookingTask();
cookingTask.wash();
cookingTask.cut();
cookingTask.deepFry();
cookingTask.fried();
...
Copy after login

Declarative programming

There is another way you are concerned about what to do. If we use lambda and functional expression to solve the above problem, it should be Like this:


public class CookingDemo {
 public void doTask(String material, Consumer<String> consumer) {
  consumer.accept(material);
 }
 public static void main(String[] args) {
  CookingDemo cookingDemo = new CookingDemo();
  cookingDemo.doTask("蔬菜", material -> System.out.println("清洗" + material));
  cookingDemo.doTask("蔬菜", material -> System.out.println(material + "切片"));
  cookingDemo.doTask("食用油", material -> System.out.println(material + "烧热"));
  cookingDemo.doTask("", material -> System.out.println("炒菜"));
 }
}
Copy after login

Here we leave the implementation details of cooking to the function library. Its biggest advantage is that you read it like a problem statement. Using this We can quickly understand its function. When you add other steps to the cooking process, it becomes very simple. You only need to call the doTask method to pass the materials in for processing. For example, I want to beat an egg before the cooking oil is heated.


cookingDemo.doTask("鸡蛋", material -> System.out.println(material + "打碎搅拌均匀"));
Copy after login

Instead of writing a method to handle eggs.

What is functional programming

The simplest answer to the question "What is functional programming" is "It is a A way of programming using functions". Everyone's understanding is different. The core is: when thinking about problems, use immutable values ​​and functions. The functions process one value and map it to another value.

Different language communities often have exclusive admiration for the characteristics of their respective languages. It's too early to talk about how Java programmers define functional programming, but it doesn't matter at all! We care about writing good code, not code that conforms to a functional programming style.

Let's imagine designing a function that inputs a string type and Boolean type parameters and outputs an integer parameter.


int pos = 0;
public Integer foo(String str, boolea flag){
 if(flag && null != str){
  pos++;
 }
 return pos;
}
Copy after login

This example has input and output, and each call may also update the value of an external variable. We call such a function a function with side effects.

In the context of functional programming, a "function" corresponds to a mathematical function: it accepts zero or more arguments, produces one or more results, and has no side effects. You can think of it as a black box which takes input and produces some output like the following function


public Integer foo(String str, boolea flag){
 if(flag && null != str){
  return 1;
 }
 return 0;
}
Copy after login

This type of function is the same as what you have in Java programming language The difference between the functions we see is very important (we cannot imagine that mathematical functions such as log or sin have side effects). In particular, when a mathematical function is called with the same parameters, the result it returns must be the same. Here, we will not consider methods like Random.nextInt for the moment.

Side effects of functions

When talking about "functional", we think What it actually says is "like a mathematical function - no side effects." From this, some subtle problems in programming arise. Do we mean that every function can only be built using functions and mathematical ideas like if-then-else? Or do we also allow some non-functional operations to be performed inside functions, as long as the results of these operations are not exposed to other parts of the system? In other words, if the program has certain side effects, but these side effects will not be perceived by other callers, can we assume that this side effect does not exist? The caller doesn't need to know about, or care about, these side effects because it has absolutely no effect on it.

When we wish to define the difference between the two, we call the first purely functional programming and the latter functional programming.

In actual programming, it is difficult for us to use Java language to complete a program in a purely functional way, because many old codes, including standard library functions, have side effects (calling Scanner.nextLine has side effects, it will Read a line from a file, usually the results of two calls are completely different). You want to write a nearly purely functional implementation of your system, and you need to make sure that your code has no side effects. Assume that such a function or method has no side effects. When entering the method body for execution, the value of a field will be incremented by one, and before exiting the method body, the value of the field will be decremented by one. For a single-threaded program, this method has no side effects and can be regarded as a functional implementation.

Our guideline for constructing functional style is that functions or methods called "functional style" can only modify local variables. In addition, the objects it refers to should be final. All reference type fields point to immutable objects.

Summarize

The above is the detailed content of Example explanation of functional programming in Java8. 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)

Remove duplicate values ​​from PHP array using regular expressions Remove duplicate values ​​from PHP array using regular expressions Apr 26, 2024 pm 04:33 PM

How to remove duplicate values ​​from PHP array using regular expressions: Use regular expression /(.*)(.+)/i to match and replace duplicates. Iterate through the array elements and check for matches using preg_match. If it matches, skip the value; otherwise, add it to a new array with no duplicate values.

What is programming for and what is the use of learning it? What is programming for and what is the use of learning it? Apr 28, 2024 pm 01:34 PM

1. Programming can be used to develop various software and applications, including websites, mobile applications, games, and data analysis tools. Its application fields are very wide, covering almost all industries, including scientific research, health care, finance, education, entertainment, etc. 2. Learning programming can help us improve our problem-solving skills and logical thinking skills. During programming, we need to analyze and understand problems, find solutions, and translate them into code. This way of thinking can cultivate our analytical and abstract abilities and improve our ability to solve practical problems.

Build browser-based applications with Golang Build browser-based applications with Golang Apr 08, 2024 am 09:24 AM

Build browser-based applications with Golang Golang combines with JavaScript to build dynamic front-end experiences. Install Golang: Visit https://golang.org/doc/install. Set up a Golang project: Create a file called main.go. Using GorillaWebToolkit: Add GorillaWebToolkit code to handle HTTP requests. Create HTML template: Create index.html in the templates subdirectory, which is the main template.

Collection of C++ programming puzzles: stimulate thinking and improve programming skills Collection of C++ programming puzzles: stimulate thinking and improve programming skills Jun 01, 2024 pm 10:26 PM

C++ programming puzzles cover algorithm and data structure concepts such as Fibonacci sequence, factorial, Hamming distance, maximum and minimum values ​​of arrays, etc. By solving these puzzles, you can consolidate C++ knowledge and improve algorithm understanding and programming skills.

Problem-Solving with Python: Unlock Powerful Solutions as a Beginner Coder Problem-Solving with Python: Unlock Powerful Solutions as a Beginner Coder Oct 11, 2024 pm 08:58 PM

Pythonempowersbeginnersinproblem-solving.Itsuser-friendlysyntax,extensivelibrary,andfeaturessuchasvariables,conditionalstatements,andloopsenableefficientcodedevelopment.Frommanagingdatatocontrollingprogramflowandperformingrepetitivetasks,Pythonprovid

Get Go modules quickly and easily with Go Get Get Go modules quickly and easily with Go Get Apr 07, 2024 pm 09:48 PM

Through GoGet, you can quickly and easily obtain Go modules. The steps are as follows: Run in the terminal: goget[module-path], where module-path is the module path. GoGet automatically downloads the module and its dependencies. The location of the installation is specified by the GOPATH environment variable.

The Key to Coding: Unlocking the Power of Python for Beginners The Key to Coding: Unlocking the Power of Python for Beginners Oct 11, 2024 pm 12:17 PM

Python is an ideal programming introduction language for beginners through its ease of learning and powerful features. Its basics include: Variables: used to store data (numbers, strings, lists, etc.). Data type: Defines the type of data in the variable (integer, floating point, etc.). Operators: used for mathematical operations and comparisons. Control flow: Control the flow of code execution (conditional statements, loops).

Unleash Your Inner Programmer: C for Absolute Beginners Unleash Your Inner Programmer: C for Absolute Beginners Oct 11, 2024 pm 03:50 PM

C is an ideal language for beginners to learn programming, and its advantages include efficiency, versatility, and portability. Learning C language requires: Installing a C compiler (such as MinGW or Cygwin) Understanding variables, data types, conditional statements and loop statements Writing the first program containing the main function and printf() function Practicing through practical cases (such as calculating averages) C language knowledge

See all articles