JAVA Lambda expressions and tutorials use

First, let me at the advantages and disadvantages Lambda expressions:

advantage:

  1: Simple

  2: easy to parallel computing, especially for convenient result, the cycle time of the calculated values ​​assigned or easily

Disadvantages:

  1: If no parallel computing, many times faster speed is not calculated For conventional cycle.

  2: not easy to debug using Debug mode

  3: Re Lamdba statement directly cast is not convenient

  4: foreach can no longer modify the values ​​in the outside

Lambda basic syntax expressions: (parameters) -> expression or (parameters) -> {statements;}

 Explain :( the Parameters ) This parameter name can be customized, but generally do see the meaning of the name, -> This must have   (parameters) -> expression or (parameters)

  -> {} method body

example:

            List <the Map <String, Object >> sevenTIME = jdbcTemplate.queryForList ( "the FROM operation_log_details the SELECT *); sevenTIME .forEach ((ss) -> {// ss similar to traverse the result set value for cycle cycle                 System.out. println (ss); // prints the result set cycle
             

                // specific codes associated logic
               });

1. Alternatively anonymous inner classes

There is no doubt, lambda expressions most used applications is an alternative anonymous inner class, implement Runnable is a classic example of an anonymous inner class. Function lambda expression is quite strong, with () -> you can replace the entire anonymous inner class! Look at the code:

If you use an anonymous inner class:

@Test
    public void oldRunable() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("The old runable now is using!");
            }
        }).start();
    }

And if you use a lambda expression

@Test public void runable() {

      new Thread(() -> System.out.println("It's a lambda function!")).start();

}

2. Using a lambda expression to iterate over a collection of 
Java collection classes daily development is often used, even said no java code is not used to the collection class. . . The most common operation is to iterate collections traversed. See the comparison:

    void iterTest public () {
        List <String> = Arrays.asList languages ( "Java", "Scala", "Python");
        // before java8
        for (each String: languages) {
            System.out.println (each);
        } // conventional manner cycle. 1
        // After java8
        languages.forEach (X -> System.out.println (X)); // the result set above embodiment 2
        languages.forEach (the System.out :: the println); / / result sets above embodiment 3
    } 

3. Implementing map with lambda expressions

@Test public void mapTest() {

    List<Double> cost = Arrays.asList(10.0, 20.0,30.0); cost.stream().map(x -> x + x*0.05).forEach(x -> System.out.println(x));

}

map function can be said that the most important functional programming is a way to go. Action is to map an object is converted into another. In our example, the cost map method is through a 0.05-fold increase in the magnitude of the output then

4. Implement the map and reduce use lambda expressions 
As mentioned in the map, how can we not mention reduce. reduce the map as one of the most important and functional programming in a few ways. . . action map is to become an object to another, and all values reduce implementation sucked into one, see:

@Test public void mapReduceTest() {

List<Double> cost = Arrays.asList(10.0, 20.0,30.0); double allCost = cost.stream().map(x -> x+x*0.05).reduce((sum,x) -> sum + x).get();      System.out.println(allCost);

}

The end result is:

63.0

If we do this thing with a for loop:

@Test public void sumTest() {

List<Double> cost = Arrays.asList(10.0, 20.0,30.0); double sum = 0;

      for(double each:cost) {

       each += each * 0.05;

        sum += each;

      } System.out.println(sum);

}

5.filter operating 
a filter operation is what we often use. When a set of operations, often need to be filtered off from the original collection part of the element.

@Test public void filterTest() {

   List<Double> cost = Arrays.asList(10.0, 20.0,30.0,40.0);

   List<Double> filteredCost = cost.stream().filter(x -> x > 25.0).collect(Collectors.toList()); filteredCost.forEach(x -> System.out.println(x));

}

The final result:

30.0 
40.0

Functional Interface (Functional Interfaces) , which represents only one interface of the abstract method, can be used to point Lambda expressions. E.g:

Consumer c = (s) -> System.out.println(s);

 

6. Predicate fit and function interface 
in addition to the language level support functional programming style, Java 8 has also added a package called java.util.function . It contains many classes for functional programming support of Java. Wherein a is the Predicate, using java.util.function.Predicate functional interface and lambda expressions, logic may be added to the API methods support more dynamic behavior with less code. Predicate interface is very suitable for making filter.

Detailed java.util.function:
  • Function <T, R>: accept a parameter T, return result R

  • Predicate <T>: accept a parameter T, returns a boolean

  • Supplier <T>: takes no parameters and returns the result T

  • Consumer <T>: accepts a parameter T, does not return results

  • UnaryOperator <T>: Inherited from Function <T, T>, T takes one argument, return the result of the same type T

  • BiFunction <T, U, R>: accepts two parameters T and U, return result R

  • BinaryOperator <T>: Inherited from BiFunction <T, T, T>, accepts two parameters of the same type T, T return the same type of results

  • Runnable: actually takes no parameters and returns no results

  • Comparable <T>: actually accepts two parameters of the same type T, return int

  • Callable <V>: takes no parameters and returns the result V

example:

public static void main(String[] args) {
        List<String> languages = Arrays.asList("Java","Python","scala","Shell","R");
        System.out.println("Language starts with J: ");


        filterTest(languages,x -> x.startsWith("J"));
        System.out.println("\nLanguage ends with a: ");


        filterTest(languages,x -> x.endsWith("a"));
        System.out.println("\nAll languages: ");


        filterTest(languages,x -> true);
        System.out.println("\nNo languages: ");


        filterTest(languages,x -> false);
        System.out.println("\nLanguage length bigger three: ");


        filterTest(languages,x -> x.length() > 4);
    }

The final output:

Language starts with J: 
Java

Language ends with a: 
Java 
scala

All languages: 
Java 
Python 
scala 
Shell 
R

No languages:

Language length bigger three: 
Python 
scala 
Shell

forEach + Lambda expressions to traverse Map and List

============Java8之前的方式==========
            Map<String, Integer> items = new HashMap<>();
            items.put("A", 10);
            items.put("B", 20);
            items.put("C", 30);
            items.put("D", 40);
            items.put("E", 50);
            items.put("F", 60);
            for (Map.Entry<String, Integer> entry : items.entrySet()) {
                System.out.println("Item : " + entry.getKey() + " Count : " + entry.getValue());
            }
            ============forEach + Lambda表达式==========
            Map<String, Integer> items = new HashMap<>();
            items.put("A", 10);
            items.put("B", 20);
            items.put("C", 30);
            items.put("D", 40);
            items.put("E", 50);
            items.put("F", 60);
            items.forEach((k,v)->System.out.println("Item : " + k + " Count : " + v));
            items.forEach((k,v)->{
                System.out.println("Item : " + k + " Count : " + v);
                if("E".equals(k)){
                    System.out.println("Hello E");
                }
            });
            二遍历List:
            ============Java8之前的方式==========

            List<String> items = new ArrayList<>();
            items.add("A");
            items.add("B");
            items.add("C");
            items.add("D");
            items.add("E");

            for(String item : items){
                System.out.println(item);
            }
            ============forEach + Lambda表达式==========
            List<String> items = new ArrayList<>();
            items.add("A");
            items.add("B");
            items.add("C");
            items.add("D");
            items.add("E");
            //输出:A,B,C,D,E
            items.forEach(item->System.out.println(item));
            //输出 : C
            items.forEach(item->{
                if("C".equals(item)){
                    System.out.println(item);
                }
            });

 

Guess you like

Origin www.cnblogs.com/ysySelf/p/10937725.html