您的位置:首页 > 编程语言 > Java开发

Java:java8 lambda retrolambda

2015-10-12 18:40 489 查看
文章来自:http://blog.csdn.net/intbird

github:https://github.com/intbird/JAVA8Lambda

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

public class Java8Lambda {

public static void main(String[] args){
//1
new Thread(()-> {System.out.println("hello intbird!");}).start();

//2
//JButton button = new JButton("show");
//button.addActionListener( q -> System.out.print("clickButton") );

//3
List list = Arrays.asList("1", "2", "3", "4");
list.forEach( (n) -> {
System.out.println(n);
});

//4 list规则
Predicate<List> condition = (n) -> n.size()>2; //>5
list.stream().filter((x) -> condition.test(list))
.forEach(name -> System.out.print(name));

//5 list item规则
Predicate<String> startWithIndex2 = (n) -> n == "2";
Predicate<String> lengthThen5 = (str) -> str.length()>0;
Predicate<String> condition1 = startWithIndex2.and(lengthThen5);
list.stream()
.filter(condition1)
.forEach(name -> System.out.println(name));

//6 list map修改
list.stream().map((o)-> o +"_index")
.forEach(System.out::println);

//7 list reduce
String listToString = list.stream().map((o) -> o + "index")
.reduce((a,b) -> a + "_\r\n_" + b)  //.reduce(((int a, int b) -> a + b)
.get().toString();
Consumer<String> out = System.out::println;
out.accept(listToString);

//1:输入且返回
Function<String[],String> test = Java8Lambda::method;
String result = test.apply(new String[]{"hello"," ","intbird"});
System.out.println(result);

//2:输入无返回
Consumer<String> test1 = System.out::println;
test1.accept("hello intbird!");

//3:无输入有返回
Callable<String> test2 = Java8Lambda::method;
try{
System.out.println(test2.call());
}catch (Exception ex){
}
Supplier<String> test3 = Java8Lambda::method;
System.out.println(test3.get());

//4:检查
Set<String> set = new HashSet<>();
set.addAll(Arrays.asList("hello"," ","intbird"));
Predicate<String> pred = set::contains;
boolean isHas = pred.test("hello");
System.out.print(isHas);

}

//part 1
//::
//    一个静态方法(类名::methname)的一个实例方法
//    特定的对象(instanceref::methname)一个超棒的方法
//    特定对象(超::methname)的一个实例方法
//    某一特定类型的任意对象(类名::methname)一类
//    建设者参考(类名::新)数组构造函数
//    参考(类型名[ ]::新)

//part 2
private static String method(String...text){
return text[0]+text[1]+text[2];
}
private static String method(){
return "hello intbird!";
}
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: