[code reconstruction and optimization] 1. Use Lambda to optimize the code and the beauty of Lambda expression

Posted by nightkarnation on Sat, 09 Nov 2019 17:52:14 +0100

I. optimize threads

//JDK 1.7 and earlier
Thread thread = new Thread(
    new Runnable() {
        @Override
        public void run() {
            System.out.println("Raw thread");
        }
    }
);
//Lambda created after JDK 1.8
Thread thread2 = new Thread(() -> {
    System.out.println("Lambda Create thread");
});

2. Optimize set operation

The core of Lambda is () - > this operation, so what does it mean? Let's look at the example of operation set

List<String> list = new ArrayList<>();
list.add("A1");list.add("A2");list.add("Z1");
list.add("Z2");list.add("B1");list.add("B2");
List<String> result = new ArrayList<>();
/**
 * .stream Operations on collections
 * .filter()filter
 * (x) -> Represents an object in a collection (objects in a collection, and entity classes come with methods)
 * !x.contains("Z") Is the expression to be filtered, which is equivalent to the content in parentheses of "if()"
 * .collect(Collectors.toList()); Convert the returned result set to List
 * */
result  = list.stream().filter(
        (x)-> !x.contains("Z")
).collect(Collectors.toList());
// Result set: [A1, A2, B1, B2]
System.out.println(result.toString());

It can be seen that () - > is an object in the operation content

Of course, you can also use another syntax to traverse a collection

result.forEach(System.out::println);

As a result, it's very simple

3. Functional interface

The first is a Brick interface with a move method. You need a type to specify the Brick type

Then define a Worker class, have a Work method, and pass in a Brick. As for the type, it is not up to you to decide. It needs to be handed over to the boss for decision. The method carries out the Brick moving: then the Brick moving method is executed and the moving is finished

Finally, a boss (main) starts to assign a worker (worker = new worker();)

Then through worker. Work ((type) - > system. Out. Println ("red" + type)); let workers move red bricks.

Through this structure, it can clearly reflect the list of what bricks are moved by the owner's freely assigned workers. At the same time, the program interface is also very clear, which is the beauty of expression!!

interface Brick {
    void move(String type);
}
class Worker{
    public void work(Brick brick){
        System.out.println("Moving bricks:");
        brick.move("brick");
        System.out.println("Move it!");
    }
    public static void main(String[] args) {
        Worker worker = new Worker();
        //Workers begin to work (bricks) - > move (red) bricks
        worker.work((type)-> System.out.println("red  " + type));
        worker.work((type)-> System.out.println("porcelain  " + type));
    }
}

 

 

Topics: Lambda JDK