以下關於lambda 表達式的使用實在java8的語法上進行的
使用Lambda表達式不僅讓代碼變的簡單、而且可讀、最重要的是代碼量也隨之減少很多,好了廢話不多說,列舉一些我在這個項目中使用的方式:
關於List的場景:
package mountain.entity;
import lombok.Data;
@Data
public class Student {
int classId;
String name;
String phone;
int age;
public Student(int classId, String name, String phone, int age) {
this.classId = classId;
this.name = name;
this.phone = phone;
this.age = age;
}
}
package mountain.lambda;
import mountain.entity.Student;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
public class ListLambda {
public static void main(String[] args) {
Student student1 = new Student(1, "tom1", "134***", 12);
Student student2 = new Student(1, "tom2", "135***", 15);
Student student3 = new Student(2, "tom3", "136***", 18);
Student student4 = new Student(2, "tom4", "137***", 20);
List<Student> list = new ArrayList<>();
list.add(student1);
list.add(student2);
list.add(student3);
list.add(student4);
// 我們需要提取list中每個user的phone信息,並且把這些phone放到一個新的集合中
List<String> phoneList = list.stream().map(s -> s.getPhone()).collect(Collectors.toList());
phoneList.forEach(System.out::println);
System.out.println("*************分割線*************");
// 我們需要提取list中每個user的name信息,提取之後拼接成字符串,中間用逗號(,)分割開
String collect = list.stream().map(s -> s.getName()).collect(Collectors.joining(","));
System.out.println(collect);
System.out.println("*************分割線*************");
// 我們需要提取list中userId等於1的一個學生,並獲取他的姓名
Optional<Student> UserFirst = list.stream().filter(s -> 1 == s.getClassId()).findFirst();
if (UserFirst.isPresent()) {
System.out.println(UserFirst.get().getName());
}
System.out.println("*************分割線*************");
// 我們需要提取list中學生年齡大於15歲的學生班級ID,並把這些班級ID放到一個字符串數組中
String[] targetIds = list.stream()
.filter(u -> u.getAge() > 15)
.map(s -> String.valueOf(s.getClassId()))
.toArray(String[]::new);
for (String id : targetIds) {
System.out.println(id);
}
System.out.println("*************分割線*************");
// 我們需要提取list中年齡最大的學生的名字
String maxAgeName = list.stream().max(Comparator.comparingInt(Student::getAge)).get().getName();
System.out.println("maxAgeName:" + maxAgeName);
System.out.println("*************分割線*************");
// 先根據學生的年齡倒敘,再取前3的名字,中間用逗號隔開
String topThreeName = list.stream().sorted(Comparator.comparingInt(Student::getAge)).limit(3).map(u -> u.getName()).collect(Collectors.joining(","));
System.out.println("topThreeName:" + topThreeName);
System.out.println("*************分割線*************");
//統計年齡大於18歲的人數
long ageCount = list.stream().filter(s -> s.getAge() > 18).count();
//統計所有學生的年齡加起來有多大
int ageSum = list.stream().mapToInt(s -> s.getAge()).sum();
System.out.println("ageCount:" + ageCount);
System.out.println("ageSum:" + ageSum);
}
}
以上只是lambda針對list在java中的基本用法,本質只是起到一個拋磚引玉的作用,更多的相關功能還需要大家實踐之後來慢慢分享,下次有時間給大家分享一下lambda關於map的相關用法,感覺有用的你可以點個贊!謝謝了