Lambda简化代码

Optional对空值的处理

比如要取user中的一个多层次数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public String getCity(User user)  throws Exception{
if(user!=null){
if(user.getAddress()!=null){
Address address = user.getAddress();
if(address.getCity()!=null){
return address.getCity();
}
}
}
throw new Excpetion("取值错误"); 
}

// 可用lambda替换为
public String getCity(User user) throws Exception{
    return Optional.ofNullable(user)
                   .map(u-> u.getAddress())
                   .map(a->a.getCity())
                   .orElseThrow(()->new Exception("取值错误"));
}

Optional对空值的判断处理

判断某个对象是否相等,如果没有则创建新的对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public User getUser(User user, String username) throws Exception{
    if(user!=null){
        String name = user.getName();
        if(username.equals(name)){
            return user;
        }
    }else{
        user = new User();
        user.setName(username);
        return user;
    }
}

// 可用lambda替换为
public User getUser(User user, String username) {
    return Optional.ofNullable(user)
                   .filter(u->username.equals(u.getName()))
                   .orElseGet(()-> {
                        User user1 = new User();
                        user1.setName(username);
                        return user1;
                   });
}

用lambda表达式实现Runnable

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// (params) -> expression
// (params) -> statement
// (params) -> { statements }
// () -> System.out.println("Hello Lambda Expressions");
// (int even, int odd) -> even + odd

new Thread(new Runnable() {
@Override
public void run() {
System.out.println("Before Java8, too much code for too little to do");
}
}).start();

// 可用lambda替换为
new Thread( () -> System.out.println("In Java8, Lambda expression rocks !!") ).start();

使用Java 8 lambda表达式进行事件处理

1
2
3
4
5
6
7
8
9
10
11
12
JButton show =  new JButton("Show");
show.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Event handling without lambda expression is boring");
}
});

// 可用lambda替换为
show.addActionListener((e) -> {
System.out.println("Light, Camera, Action !! Lambda expressions Rocks");
});

使用lambda表达式对列表进行迭代

1
2
3
4
5
6
7
8
9
10
11
List features = Arrays.asList("Lambdas", "Default Method", "Stream API", "Date and Time API");
for (String feature : features) {
System.out.println(feature);
}

// 可用lambda替换为
List features = Arrays.asList("Lambdas", "Default Method", "Stream API", "Date and Time API");
features.forEach(n -> System.out.println(n));

// 也可以替换为
features.forEach(System.out::println);