1、准备工作:
编写一个student类
package com.stream;
import lombok.Data;
@Data
public class Student {
private String name;
private Integer id;
}
2、遍历打印
public void printStu(List<Student> list){
list.forEach(student -> System.out.println(student));
}
3、遍历(注意:遍历时可以使用外部遍历但是默认会被final修饰)
public void foreach(List<Student> list){
list.forEach(student -> {
student.setId(2);
student.setName("娃哈哈");
});
}
4、转list
public void toList(List<Student> list){
List<Integer> collect = list.stream().map(Student::getId).collect(Collectors.toList());
List<String> collect2 = list.stream().map(Student::getName).collect(Collectors.toList());
}
4、复杂的转list
//获取所有的ID如果没有名字,将id置为-1
List<Integer> collect = list.stream().map(stu->{
String name = stu.getName();
if (name==null){
return -1;
}
return stu.getId();
}).collect(Collectors.toList());
}
5、转map
public void toMap(List<Student> list){
//key是id value是name
Map<Integer, String> collect = list.stream().collect(Collectors.toMap(Student::getId, Student::getName));
}
6、复杂的转map
public void toMap2(List<Student> list) {
//key是id value是name
Map<Integer, String> collect = list.stream().collect(
Collectors.toMap(
k -> {
Student stu = (Student) k;
业务加工逻辑。。。。
return stu.getId();
},
v -> {
Student stu = (Student) v;
//业务加工逻辑。。。。
return stu.getName();
})
);
}
7、排序
public List<Student> sort(List<Student> list) {
return list.stream().sorted(Comparator.comparingInt(Student::getId))
.collect(Collectors.toList());
}
8、取最大值
public Student getMax(List<Student> list) {
Optional<Student> max = list.stream().max(Comparator.comparingInt(Student::getId));
return max.get();
}
9、如果想用自己的对象定义的排序方法
(前提,对象必须继承Comparable接口实现compareTo方法)
public Student getMax(List<Student> list) {
Optional<Student> max = list.stream().max(Comparator.naturalOrder());
return max.get();
}