import javax.swing.text.html.Option;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
//jdk8 函数式编程练习
/*
函数式编程,四个核心函数
Function
Supplier
Consumer
Predicate
*/
class Student {
private String name;
private int score;
public Student() {
}
public Student(String name, int score){
this.name = name;
this.score = score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
}
public class Main3 {
public static void main(String[] args) {
List<Student> stus = new ArrayList<>();
stus.add(new Student("张晓明",25));
stus.add(new Student("朱德华",36));
stus.add(new Student("刘小胡",98));
stus.add(new Student("泽铭",45));
List<String> names = stus.stream().
map(Student::getName).
collect(Collectors.toList());
System.out.println(names);
List scores = stus.stream().
map(Student::getScore).
filter(x -> x >= 40).
collect(Collectors.toList());
stus.stream().filter(s -> s.getScore() > 30).forEach(e -> System.out.println(e.getName()));
System.out.println(scores);
Arrays.asList("aaa","vvvv","vd","dddeee")
.stream()
.filter(s -> s.length() > 2)
.forEach(System.out::println);
Arrays.asList("aaa","vvvv","vd","dddeee")
.stream()
.map(s -> s.toUpperCase())
.forEach(System.out::println);
System.out.println("------------------------");
//自然排序,也可传入Comparator进行自定义排序
Optional op = Arrays.asList("aaa","vvvv","vd","dddeee")
.stream()
.sorted((y,x) -> x.compareTo(y))
.findFirst();//返回一个Optional对象
//findFirst方法是中止操作,以后不可进行forEach遍历;
System.out.println(op.get());
Long cnt = Arrays.asList("aaa","vvvv","vd","dddeee").stream().count();
System.out.println(cnt);
//其他两个中止操作, reduce 和Python中的功能相同, collect
String res = Arrays.asList("aaa","vvvv","vd","dddeee")
.stream()
.sorted()
.reduce("", String::concat);
System.out.println(res);
//有没有串的长度大于3的 anyMatch
boolean flag = Arrays.asList("aaa","vvvv","vd","dddeee")
.stream()
.anyMatch(s -> s.length() > 3);
System.out.println(flag);
//找到最大值
Optional<Integer> opt4 = Arrays.asList(1,2,5,6,9).stream()
.max(Integer::compareTo);//方法引用
System.out.println(opt4.get());
}
}