Function函数式接口
image.png
Function function = new Function<String, String>() {
@Override
public String apply(String str) {
return str;
}
};
// 使用lamba简化
function = (str)->{
return str;
};
System.out.println(function.apply("123"));
Predicate断定型接口
image.png
Predicate<String> predicate = new Predicate<String>() {
@Override
public boolean test(String str) {
return str.isEmpty();
}
};
predicate = (str)->{
return str.isEmpty();
};
System.out.println(predicate.test("33")); // false
System.out.println(predicate.test("")); // true
Consumer消费型接口
image.png
Consumer<String>consumer = new Consumer<String>() {
@Override
public void accept(String str) {
System.out.println(str);
}
};
consumer = (str)->{System.out.println(str);};
consumer.accept("hello world..");
供给型接口
image.png
Supplier<String> supplier = new Supplier<String>() {
@Override
public String get() {
return "supper a str";
}
};
supplier = ()->{return "supper a str by lambda";};
System.out.println(supplier.get());
stream流式计算
package com.test.fun;
import java.util.Arrays;
import java.util.List;
public class Fun4 {
public static void main(String[] args) {
User u1 = new User(1, "aa", 21);
User u2 = new User(2, "bb", 22);
User u3 = new User(3, "cc", 23);
User u4 = new User(4, "dd", 24);
User u5 = new User(5, "ee", 25);
User u6 = new User(6, "ee", 26);
/**
* 筛选:
* 1. id必须是偶数
* 2. 年龄必须大于23岁
* 3. 用户名转为大写字母
* 4. 用户名字母倒着排序
* 5. 只输出一个用户
*/
List<User> list = Arrays.asList(u1, u2, u3, u4, u5, u6);
list.stream().filter((u)->{return u.getId()% 2==0;})
.filter((u)->{return u.getAge() > 23;})
.map(u->{return u.getName().toUpperCase();})
.sorted((uu1, uu2)->{return uu2.compareTo(uu1);})
.limit(1)
.forEach(System.out::println);
}
}
class User {
private int id;
private String name;
private int age;
public User(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", age=" + age + "]";
}
}
网友评论