Java8 Practical Combat [1-4] Chapter Essentials Notes

Note: The explanations in Chapters 1 to 4 of "Java8 Practical Combat" focus on theory, and you need to slowly read and understand from the book. The article here is mainly for the purpose of practical notes, so I will briefly note several important points of Java8 Practical Combat.

1. Understand Lambda expressions

A new tool in Java 8 to solve this problem - Lambda expressions. It allows you to express a behavior or pass code very concisely. Now you can think of a Lambda expression as an anonymous function, which is basically a method without a declared name, but like an anonymous class, it can also be passed as a parameter to a method.

Shows how to build a Lambda, where it can be used, and how you can use it to make your code cleaner. We'll also cover some new stuff like type inference and important new interfaces in the Java 8 API. Finally, we'll introduce method references, a useful new feature often used in conjunction with lambda expressions.

It makes the code no longer very verbose and improves programmers' enthusiasm for using behavior parameterization in practice.

/**
 * @author chuan
 * @version 1.0
 * @description: Lambda表达式使用
 */
@RestController
@RequestMapping("/test")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class TestController {

    /**
     * Lambda表达式使用
     */
    @GetMapping("/printlnTest")
    public void printlnTest(){
        List<String> strings = Arrays.asList("A", "B", "C");
        // 打印结果 A、B、C
        strings.forEach(System.out::println);

        List<String> values = strings.stream().filter(s -> s.equals("B")).collect(Collectors.toList());
        // 打印结果 B
        values.forEach(System.out::println);
    }

}

2. Java 8 adds a Stream API in java.util.stream

Java 8 adds a Stream API in java.util.stream;

Stream<T> is a series of items of type T. You can now think of it as a fancy iterator.

Many methods of the Stream API can be chained together to form a complex pipeline, just like the Unix commands chained in the previous example. The key thing driving this approach is that now you can write Java 8 programs at a higher level of abstraction: the idea becomes to turn this stream into that stream (just like when writing database queries) ) instead of working on one project at a time. Another benefit is that Java 8 can transparently take irrelevant parts of the input to several CPU cores to execute your Stream operation pipeline separately - this is almost free parallelism, and there is no need to bother with Thread.

3. Use behavior parameterization to pass code to methods

Another programming concept added in Java 8 is the ability to pass code through APIs. This sounds really abstract.

In the Unix case, you may want to tell the sort command to use a custom sort. Although the sort command supports various predefined types of sorting, such as reverse order, through command line parameters, this is limited after all. For example, you have a bunch of invoice codes in a format similar to 2013UK0001, 2014US0002... The first four digits represent the year, the next two letters represent the country, and the last four digits are the customer's code.

You may want to sort invoices by year, customer code, or even country. What you really want is to be able to give the sort command an argument that lets the user define the order: pass the sort command a separate piece of code. So, to apply it directly to Java, you need to let the sort method use a custom order for comparison.

You could write a compareUsingCustomerId code to compare two invoices, but before Java 8, you couldn't pass this method to another method. You could create a Comparator object and pass it to the sort method, as explained at the beginning of this chapter, but this is verbose and makes the idea of ​​reusing existing behavior less clear.

Java 8 adds the ability to pass a method (your code) as a parameter to another method. depicts this line of thinking. We call this concept behavioral parameterization. What's so important about it?

The Stream API is built on the idea of ​​parameterizing the operation behavior by passing code. When you pass compareUsingCustomerId in, you parameterize the sort behavior.

    public void demo(){

        List<String> collect = list.stream()
                // 条件过滤
                .filter(user -> user.getUId() > 10)
                // 正序排序
                .sorted(Comparator.comparing(User::getUId))
                // 取出名字
                .map(User::getName)
                // 取出前两条
                .limit(2)
                // 去重
                .distinct()
                // 转出集合
                .collect(toList());
    }

4. Java 8’s stream implementation is easier to implement than Java’s existing thread API

Java 8's streams make it easier to implement parallelism than Java's existing thread API. Therefore, although you can use synchronized to break the "no shared mutable data" rule, this is equivalent to going against the entire system, because it makes All optimizations around this rule are meaningless. The cost of using synchronized across multiple processor cores is often much greater than you expect because synchronization forces code to be executed sequentially, which is contrary to the purpose of parallel processing.


These two points (no shared mutable data, the ability to pass methods and functions as code to other methods) are the cornerstones of what we commonly call the functional programming paradigm, which we discuss in detail in Chapters 13 and 14 . In contrast, in the imperative programming paradigm, the program you write is a series of instructions that change state. The "no shared mutable data" requirement means that a method is fully described by the way it converts parameter values ​​into results; in other words, it behaves like a mathematical function with no visible side effects.

    public void demo(){
        /**
         * 为了利用多核架构并行执行这段代码,你只需要把stream()换成parallelStream()
         * List<String> collect = userAges.parallelStream()
         */
        List<String> collect = list.parallelStream()
                // 条件过滤
                .filter(user -> user.getUId() > 10)
                // 正序排序
                .sorted(Comparator.comparing(User::getUId))
                // 取出名字
                .map(User::getName)
                // 取出前两条
                .limit(2)
                // 去重
                .distinct()
                // 转出集合
                .collect(toList());
    }

5. Summary

The summary may be this sentence: the language needs to be continuously improved to keep up with hardware updates or meet the expectations of programmers (if you are not convinced enough, consider that COBOL was once one of the most important languages ​​​​in business).

To persist, Java must improve by adding new features, and changes are only meaningful if the new features are used by people. So, with Java 8, you are protecting your career as a Java programmer. Beyond that, we have a feeling you're going to love the new features in Java 8. Just ask anyone who has used Java 8 and see if they would go back.

Also, to use an ecosystem analogy, the new Java 8 features enable Java to conquer programming task territories now occupied by other languages, so Java 8 programmers need to learn it even more.

Guess you like

Origin blog.csdn.net/amosjob/article/details/126218634