Skip to content

Instantly share code, notes, and snippets.

@wangshizhan
Last active April 13, 2023 15:37
Show Gist options
  • Save wangshizhan/fd868bd9a81934e9549e8f7cce3c2763 to your computer and use it in GitHub Desktop.
Save wangshizhan/fd868bd9a81934e9549e8f7cce3c2763 to your computer and use it in GitHub Desktop.
import java.util.function.*;
import java.util.*;
class TestClass {
public static void main(String[] args) {
// 匿名内部类、lambda表达式、方法引用
accept(200, (x) -> System.out.println(x));
Random r = new Random();
List<Integer> li = get(3, () -> r.nextInt(10));
li.forEach(x->System.out.println(x));
System.out.println(func("abc", n -> n.substring(0,1)));
System.out.println(func("bca", new Function<String, String>(){
@Override
public String apply(String s){
return s.substring(0,1);
}
}));
System.out.println(func("ab c ", n -> n.trim()));
List<Integer> fli = filterInt(li, x -> (x > 5));
System.out.println(li);
System.out.println(fli);
// 当要传递给Lambada的操作,已经有实现的方法,可以使用方法引用 操作符 ::
// 对象::实例方法
// 类::静态方法
// 类::实例方法
Consumer<String> c1 = System.out::println;
c1 = (x) -> System.out.println(x);
c1.accept("str");
Comparator<Integer> c2 = (x, y) -> Integer.compare(x, y);
c2 = Integer::compare;
System.out.println(c2.compare(1, 4));
BiPredicate<String,String> c3 = (x, y) -> x.equals(y);
c3 = String::equals;
System.out.println(c3.test("11", "11"));
// 构造器引用与函数式接口相结合,自动与函数式接口方法兼容 操作符 ClassName::new
Supplier<User> u1 = User::new;
u1 = () -> new User();
System.out.println(u1.get());
Function<String, User> u2 = (x) -> new User(x);
u2 = User::new;
System.out.println(u2.apply("小虎"));
Function<Integer, String[]> f= String[]::new;
System.out.println(f.apply(10).length);
}
// 1、Consumer 消费型接口
static void accept(double c, Consumer<Double> x){
x.accept(c);
}
// 2、Supplier 供给型接口 相当于容器
static List<Integer> get(int n, Supplier<Integer> s1){
List<Integer> li = new ArrayList<Integer>();
for (int i = 0; i < n; i++) {
li.add(s1.get());
}
return li;
}
// 3、Function 函数型接口
static String func(String s, Function<String, String> fun){
return fun.apply(s);
}
// 4、Predicate 断言型接口
static List<Integer> filterInt(List<Integer> li, Predicate<Integer> p){
List<Integer> l = new ArrayList<Integer>();
for(Integer integer : li){
if(p.test(integer)){
l.add(integer);
}
}
return l;
}
}
class User{
String name;
public User(){
}
public User(String name){
this.name = name;
}
public String getName(){
return this.name;
}
public void setName(String name){
this.name = name;
}
public String toString(){
return "user: [name: " + this.getName() + " ]";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment