什么是Lambda
Lambda 表達(dá)式,也可稱為閉包,它是推動 Java 8 發(fā)布的最重要新特性;
Lambda 允許把函數(shù)作為一個方法的參數(shù)(函數(shù)作為參數(shù)傳遞進(jìn)方法中);
使用 Lambda 表達(dá)式可以使代碼變的更加簡潔緊湊。
Lambda基本語法:
(parameters) -> expression
或
(parameters) ->{ statements; }
常見使用場景:
-
新建User實(shí)體類
public class User {
private String userId;
private Integer age;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"userId='" + userId + '\'' +
", age=" + age +
'}';
}
}
//新建一個用戶集合
List<User> userList = new ArrayList<>();
//遍歷插入10個user對象
for (int i = 0; i <= 10; i++) {
User user = new User();
user.setUserId(String.valueOf(i));
user.setAge(i);
userList.add(user);
}
//遍歷輸出age
userList.forEach(user -> System.out.print("age:" + user.getAge()+" "));
//獲取userId的集合
//傳統(tǒng)方式
List<String> oldMethod = new ArrayList<>();
for (User user : userList) {
oldMethod.add(user.getUserId());
}
//[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
System.out.println(oldMethod);
//使用lambda結(jié)合stream
//[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
List<String> newMethod = userList.stream().map(user -> user.getUserId()).collect(Collectors.toList());
System.out.println(newMethod);
//取出userId大于5的集合
List<String> list = newMethod.stream().filter(x -> Integer.valueOf(x) > 5).collect(Collectors.toList());
//[6, 7, 8, 9, 10]
System.out.println(list);
//按升序排序獲取age的前兩位
List<User> userSortList = userList
.stream()
.sorted(Comparator.comparing(User::getAge))
.limit(2)
.collect(Collectors.toList());
//[User{userId='0', age=0}, User{userId='1', age=1}]
System.out.println(userSortList.toString());
//按降序排序獲取age的前兩位
List<User> userSortList2 = userList
.stream()
.sorted(Comparator.comparing(User::getAge).reversed())
.limit(2)
.collect(Collectors.toList());
//[User{userId='10', age=10}, User{userId='9', age=9}]
System.out.println(userSortList2.toString());
小小總結(jié)
正如你所看到的,熟練使用Lambda表達(dá)式后,這不僅讓代碼變的簡單、而且可讀,最重要的是代碼量也隨之減少很多,代碼也更加優(yōu)雅了。