语法例子
LambdaGrammarTest lambdaTest = new LambdaGrammarTest();
// 1. 能够推导出类型的,可以不写类型
String[] planets = new String[] { "11", "22", "33" };
Arrays.sort(planets, (first, second) -> first.length() - second.length());
Arrays.sort(planets, String::compareToIgnoreCase);
// 2. 删除list中所有的null值, Predicate 接口
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.removeIf(x -> x == null);
// 3. BiFunction<T, U, R>
// T - 表示第一个参数, U - 表示第二个参数, R - 表示返回结构result
BiFunction<String, String, Integer> comp = (first, second) -> first.length() - second.length();
System.out.println(comp.apply("11", "222"));
java7_biFunction();
java8_biFunction();
// 4. ::
// (1) 对象方法 object::instanceMethod 等同于 x->object.instanceMethod(x);
// (x,y)->object.instanceMethod(x,y);
String string = new String("123456");
MyFunction3 myFunction3 = string::substring;
System.out.println(myFunction3.test(2));
MyFunction4 myFunction4 = string::substring;
System.out.println(myFunction4.test(2, 5));
// (2) 静态方法 Object::staticMethod 等同于 x->Object.staticMethod(x);
// (x,y)->Object.staticMethod(x,y);
MyFunction5 myFunction5 = System.out::println;
myFunction5.test("*******");
MyNumeric2 myNumeric2 = Math::max;
System.out.println(myNumeric2.test(2, 5));
// (3) 对象方法 Object::instanceMethod, 等同于 x,y->x.instanceMethod(y)
Arrays.sort(planets, String::compareToIgnoreCase);
MyFunction6 myNumeric6 = string::equalsIgnoreCase;
myNumeric6.test("123456");
MyFunction7 myNumeric7 = String::equalsIgnoreCase;
myNumeric7.test("123456", "123456");
//也可用来调用方法
Person[] personArray = new Person[]{new Person("Tom"),new Person("Jack"),new Person("Alice")};
Arrays.sort(personArray, Comparator.comparing(Person::getName));
for (Person person : personArray) {
System.out.println(person.getName());
}
MyFunc<Integer> myClassFunc = MyClass<Integer>::new; //相当于 x -> new MyClass<Integer>(x);
MyClass<Integer> func = myClassFunc.func(100);
System.out.println(func.getVal());
MyFunc2<MyClass<Integer>, Integer> myClassFunc2 = MyClass<Integer>::new;
MyClass<Integer> func2 = myClassFactory(myClassFunc2, 1000);
System.out.println(func2.getVal());
// (4) 使用this
lambdaTest.foo();
// (5) 使用super
new B().foo("Test Super::method");
// (6) 构造器引用 ==>可用来做批量的类型转换
//int[]::new ==> x->new int[x];
ArrayList<String> personStrings = new ArrayList<String>();
personStrings.add("Tom");
personStrings.add("Jack");
//可用来做批量的类型转换, 结合stream & map 用法, 过滤
//得到List
Stream<Person> personStream = personStrings.stream().map(Person::new); //Person::new 相当于 x->new Person(x);调用对应的构造器
List<Person> persons = personStream.collect(Collectors.toList());
for (Person person : persons) {
System.out.println(person.getName());
}
//得到数组
personStream = personStrings.stream().map(Person::new);
Person[] personArrays = personStream.toArray(Person[]::new);
for (Person person : personArrays) {
System.out.println(person.getName());
}
//5. Lambda表达式中的变量名不能和局部的其它变量名相同
//6. Lambda表达式必须引用值不会改变的变量
//7. 使用Lambda遍历list集合 forEach
personStrings.forEach(n->System.out.println(n));
//8. 其它接口
MyNumber num = () -> 555;
System.out.println(num.getValue());
num = () -> Math.random() * 100;
System.out.println(num.getValue());
System.out.println(num.getValue());
System.out.println(num.getValue());
MyNumeric numic = (n) -> (n % 2) == 0;
System.out.println(numic.test(8));
numic = (n) -> n > 8;
System.out.println(numic.test(8));
MyNumeric2 numic2 = (x, y) -> x * y;
System.out.println(numic2.test(8, 10));
numic2 = (int x, int y) -> x - y;
System.out.println(numic2.test(8, 10));
MyFunction myFunction = (n) -> {
int result = 1;
for (int i = 1; i <= n; i++) {
result = result * i;
}
return result;
};
System.out.println(myFunction.test(5));
MyFunction2 myFunction2 = (str) -> {
return StringUtils.reverse(str);
};
System.out.println(myFunction2.test("qwert"));
SomeFunction<Integer> someFunction1 = (n) -> {
int result = 1;
for (int i = 1; i <= n; i++) {
result = result * i;
}
return result;
};
System.out.println(someFunction1.test(5));
SomeFunction<String> someFunction2 = (str) -> {
return StringUtils.reverse(str);
};
System.out.println(someFunction2.test("qwert"));
String testingStr = "test string";
String test1 = "test1";
String tOperation1 = tOperation((str) -> {
if (StringUtils.isBlank(str)) {
throw new Exception();
}
// Local variable test1 defined in an enclosing scope must be final
// or effectively final
// test1="";
return StringUtils.reverse(str + test1);
} , testingStr);
System.out.println(tOperation1);
String tOperation2 = tOperation((str) -> str.toUpperCase(), testingStr);
System.out.println(tOperation2);
Function<Integer, Integer> factorial = (n) -> {
// ...
return n;
};
System.out.println(factorial.apply(5));
Timer timer = new Timer(1000, xx -> System.out.println(new Date() + "+++++"));
timer.start();
// Thread.slp(1000000);
Runnable runnable = ()->{
System.out.println("runnable action 1");
System.out.println("runnable action 2");
System.out.println("runnable action 3");
};
repeat(2, runnable);
辅助方法
public static void repeat(int n, Runnable action){
for (int i = 0; i < n; i++) {
action.run();
}
}
static String tOperation(SomeFunction<String> someFunction, String str) throws Exception {
return someFunction.test(str);
}
private static void java7_biFunction() {
BiFunction<String, String, String> bi = new BiFunction<String, String, String>() {
@Override
public String apply(String t, String u) {
return t + u;
}
};
Function<String, String> func = new Function<String, String>() {
@Override
public String apply(String t) {
return t + "-then";
}
};
System.out.println(func.apply("test"));// test-then
System.out.println(bi.apply("java2s.com", "-tutorial"));// java2s.com-tutorial
System.out.println(bi.andThen(func).andThen(func).apply("java2s.com", "-tutorial"));// java2s.com-tutorial-then-then
}
private static void java8_biFunction() {
// java8新特性,lambda表达式
BiFunction<String, String, String> bi = (x, y) -> {
return x + y;
};
Function<String, String> func = x -> x + "-then";
System.out.println(func.apply("test"));// test-then
System.out.println(bi.apply("java2s.com", "-tutorial"));// java2s.com
// tutorial
System.out.println(bi.andThen(func).andThen(func).apply("java2s.com", "-tutorial"));// java2s.com-tutorial-then-then
}
private void foo(){
MyFunction8 myNumeric8 = this::foo2;
myNumeric8.test("MyFunction8 foo2");
}
private void foo2(String x){
System.out.println("foo2-----"+x);
}
//Lambda expression's parameter x cannot redeclare another local variable defined in an enclosing scope.
private void foo3(String x){
// MyFunction2 myFunction2 = x->x;
}
static <R,T> R myClassFactory(MyFunc2<R, T> cons, T v){
return cons.func(v);
}
函数式接口
interface MyNumber {
double getValue();
}
interface MyNumeric {
boolean test(int n);
}
interface MyNumeric2 {
int test(int x, int y);
}
interface MyFunction {
int test(int n);
}
interface MyFunction2 {
String test(String str);
}
interface MyFunction3 {
String test(int x);
}
interface MyFunction4 {
String test(int x, int y);
}
interface MyFunction5 {
void test(String x);
}
interface MyFunction6 {
boolean test(String x);
}
interface MyFunction7 {
boolean test(String x, String y);
}
interface MyFunction8 {
void test(String x);
}
interface MyFunction9 extends Runnable{
}
interface SomeFunction<T> {
T test(T t) throws Exception;
}
class A{
void foo(String x){
System.out.println("Parent A foo:"+x);
}
}
class B extends A{
void foo(String x){
MyFunction8 xxx = super::foo;
xxx.test(x);
}
}
interface MyFunc<T>{
MyClass<T> func(T t);
}
interface MyFunc2<R, T>{
R func(T t);
}
class MyClass<T>{
private T val;
public MyClass() {
val = null;
}
public MyClass(T v) {
val = v;
}
T getVal(){
return val;
}
}
class Person{
public Person() {
// TODO Auto-generated constructor stub
}
public Person(String name) {
this.name=name;
}
public Person(String name,String firstName,String lastName) {
this.name=name;
this.firstName=firstName;
this.lastName=lastName;
}
private String name;
private String firstName;
private String lastName;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}