Example explanation of functional programming in Java8
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(); ...
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("炒菜")); } }
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 + "打碎搅拌均匀"));
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; }
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; }
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!

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version
Chinese version, very easy to use

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function