lambda表达式
import org.junit.Test;
import java.io.PrintStream;
import java.util.Comparator;
import java.util.function.*;
public class LambdaTest {
@Test
public void test1() {
Runnable r1 = new Runnable() {
@Override
public void run() {
System.out.println("r1");
}
};
r1.run();
Runnable r2 = () -> System.out.println("r2");
r2.run();
Consumer<String> consumer = new Consumer<String>() {
@Override
public void accept(String s) {
System.out.println("consumer");
}
};
Consumer<String> consumer1 = (String s) -> System.out.println(s);
consumer1.accept("consumer1");
Consumer<String> consumer2 = (s) -> System.out.println(s);
consumer2.accept("consumer2");
Consumer<String> consumer3 = s -> System.out.println(s);
consumer3.accept("consumer3");
Comparator<Integer> c1 = new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
System.out.println(o1);
System.out.println(o2);
return o1.compareTo(o2);
}
};
System.out.println(c1.compare(12, 34));
Comparator<Integer> c2 = (o1, o2) -> {
System.out.println(o1);
System.out.println(o2);
return o1.compareTo(o2);
};
System.out.println(c2.compare(23, 56));
Comparator<Integer> c3 = new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1.compareTo(o2);
}
};
System.out.println(c3.compare(12, 34));
Comparator<Integer> c4 = (o1, o2) -> o1.compareTo(o2);
System.out.println(c4.compare(23, 56));
}
@Test
public void test2() {
PrintStream ps = System.out;
Consumer<String> consumer = ps::println;
consumer.accept("consumer");
Person person = new Person("tom", 23);
Supplier<String> supplier = person::getName;
System.out.println(supplier.get());
Comparator<Integer> c1 = Integer::compare;
System.out.println(c1.compare(12, 45));
Comparator<String> comparator = String::compareTo;
System.out.println(comparator.compare("abd", "ase"));
BiPredicate<String, String> biPredicate = String::equals;
System.out.println(biPredicate.test("qwe", "qwe"));
}
@Test
public void test3() {
Supplier<Person> supplier1 = new Supplier<Person>() {
@Override
public Person get() {
return new Person();
}
};
System.out.println(supplier1.get());
Supplier<Person> supplier2 = () -> new Person();
System.out.println(supplier2.get());
Supplier<Person> supplier3 = Person::new;
System.out.println(supplier3.get());
Function<String,Person> function1 = name -> new Person(name);
System.out.println(function1.apply("tom"));
Function<String,Person> function2 = Person :: new;
System.out.println(function2.apply("jerry"));
BiFunction<String,Integer,Person> biFunction1 = (name,age) -> new Person(name,age);
System.out.println(biFunction1.apply("tom", 23));
BiFunction<String,Integer,Person> biFunction2 = Person::new;
System.out.println(biFunction2.apply("jerry", 24));
}
@Test
public void test4(){
Function<Integer,String[]> function1 = length -> new String[length];
String[] arr1 = function1.apply(10);
Function<Integer,String[]> function2 = String[]::new;
String[] arr2 = function2.apply(10);
}
}