This is the 14th day of my participation in Gwen Challenge

One, foreword

What is theLambda

  • lambdaExpressions allow us to transfer behavior to functions
  • There’s a mathematical model that naturally lends itself to parallelization, namelyLambdaExpression.
  • This mathematical model later evolved into another programming paradigm in computing, functional programming (Function Programming)


Disadvantages of traditional collection:

  1. JavaforLoops are serial and must be processed once in the order of the elements in the collection
  2. The collection framework cannot be optimized for heap control flow, such as parallel short-circuiting by sorting (short-circuiting) evaluation and lazy evaluation improve performance


lambdaAdvantage:

  1. Partition: Internal iteration external iteration

    • Previous external iteration responsibilities: What to do (business requirements), how to do it (how to traverse)
    • Then internal iteration responsibilities: What to do
  2. How do YOU do that


Why studyLambda?

  • Better understanding of functional, which allows you to write code in a functional style
  • Easy to use against lists (Lists) and set (Collections) data is extracted, filtered and sorted.





Second, the use of

What do I need to learn?

  1. Lambdaexpression
  2. Functional interface
  3. flowAPI

(1)lambdaExpression implementationRunnable

Used mainly for anonymous classes.

// Before, we usually use:
new Thread(new Runnable() {
    @Override
    public void run(a) {
        System.out.println("not use lambda");
    }
}).start();

// with lambda:
new Thread( () -> System.out.println("use lambda")).start();
Copy the code

Grammar:

Expected inputs on the left and expected outputs on the right

  1. (params) -> expression
  2. (params) -> statement
  3. (params) -> { statements }The box() - > {}Instead of an entire anonymous class

() -> system.out.println (” Hello lambda!”) )

Accept: (int even, int odd) -> even + odd


(2)lambdaAn expression iterates over a list

Easier to do iterations and parallel processing of collection elements

List<String> features = Arrays.asList("lambdas"."default"."stream api");
        
/ / before:
for (String feature : features) {
     System.out.println(feature);
}
        
// after lambda:
features.forEach(item -> System.out.println(item));
        
// More concise:
features.forEach(System.out::println);
Copy the code


(3) UselambdaExpressions and functional interfacesPredicate

Java. Util. The function. The Predicate function interface, can add logic to the API method, with less code to support more dynamic behavior. The Predicate interface is useful for filtering:

public void testPredicate(a) {

    List<String> languages = Arrays.asList("Java"."JavaScript"."Scala"."C++"."Haskell");

    System.out.println("Language which starts with J: ");
    filter(languages, (str) -> str.startsWith("J"));

    // OR after
    filter2(languages, (str) -> str.startsWith("J"));

}

private void filter(List<String> names, Predicate<String> condition) {
    for (String name: names) {
        if (condition.test(name)) {
            System.out.println(name + ""); }}}private void filter2(List<String> names, Predicate<String> condition) {
    names.stream().filter((name) -> (condition.test(name))).forEach((name) -> {
        System.out.println(name + "");
    });
}
Copy the code


PredicateThe interface allows testing of multiple conditions:

You can combine two or more predicates into one. And () or (xor) ()

        Predicate<String> startsWithJ = (n) -> n.startsWith("J");
        Predicate<String> fourLetterLong = (n) -> n.length() == 4;

        languages.stream().filter(startsWithJ.and(fourLetterLong))
                .forEach((n) -> System.out.println("Name, which starts with 'J' and four letter long is : " + n ));

Copy the code


(4)lambdaexpressionMapThe sample

A map allows objects (or values) to be transformed, and every element in the flow will be transformed.

List<Integer> costBeforeTax = Arrays.asList(100.200.300.400.500);

for (Integer cost : costBeforeTax) {
    double price = cost + 12. * cost;
    System.out.println(price);
}

// Use lambda expressions
costBeforeTax.stream().map((cost) -> cost + 12. * cost)
    .forEach(System.out::println);
Copy the code


(5)lambdaexpressionReduceThe sample

Reduce () is also a fold operation that combines all values into one.

In SQL, the sum() avg() count() aggregation function is actually a reduce operation.

Accepts multiple values and returns a value:

List<Integer> costBeforeTax = Arrays.asList(100.200.300.400.500);
double total = 0;
for (Integer cost : costBeforeTax) {
    double price = cost + 12. * cost;
    total = total + price;
}

System.out.println("Total : " + total);

/ / after
double bill = costBeforeTax.stream().map((cost) -> cost + 12. * cost)
    .reduce((sum, cost) -> sum + cost)
    .get();
System.out.println("Bill : " + bill);
Copy the code


(6)lambdaExpression filteringJavaA collection of

Create a list of strings by Filter:

List<String> strList = Arrays.asList("English"."Chinese"."French"."KaKoa");

List<String> filtered = strList.stream().filter(x -> x.length() > 2).collect(Collectors.toList());

System.out.printf("Original List : %s, filtered list : %s", strList, filtered);
Copy the code


(7) The stream

Add a new stream java.util.stream. stream to the library for aggregation

Where Stream

represents an object reference, there are also a series of specialization streams, such as IntStream for an integer

The operations of streams can be combined into pipelines

Such as:

shapes.stream()
      .filter(s -> s.getColor() == BLUE)
      .forEach(s -> s.setColor(RED));
Copy the code

Calling stream() on a Collection generates a stream view of the Collection elements.

  • filter()Filter to produce a stream that contains only blue
  • forEach()Traverse, and set the action to red

Pipelining can be executed serially or in parallel, and parallelism or serialization are properties of streams. Unless the display requires a parallel stream, the JDK will always return a serial stream. (Serial streams can be converted to parallel streams using the parallel() method.)


Streams have two characteristics:

  1. Laziness:

    • StreamNaturally inert – only produced on demand.
    • That is, it is like an infinite sequence that produces values only when you ask for them, and values produce only values that you ask for.
    • I can give you anything you want!!
  2. Cache:

    • Another property of streams is that they remember (memoize) the values they have generated.
    • Actually: cache ~ ~ ~ hahaha!!
    • When the stream generates a new value on demand, it caches it between returns.


Question: How do parallel streams parallel?

CPU, multithreading at the same time, disorder.