1.用lambda表达式实现map
List cost = Arrays.asList(10.0,20.0,30.0);
cost.stream().forEach(x-> System.out.println(x));
System.out.println("----------");
cost.stream().map(x -> x + x*0.05).forEach(x -> System.out.println(x));
2. 用lambda表达式对集合进行迭代
List languages = Arrays.asList("java","scala","python");
//before java8
for(String each:languages) {
System.out.println(each);
}
System.out.println("-------");
//after java8
languages.forEach(x -> System.out.println(x));
languages.forEach(System.out::println);
3.用lambda表达式实现map与reduce
//map+reduce+lambda表达式
List cost = Arrays.asList(10.0, 20.0,30.0);
double allCost = cost.stream().map(x -> x+x*0.05).reduce((sum,x) -> sum + x).get();
System.out.println(allCost);//63.0
等同于:
List cost = Arrays.asList(10.0, 20.0,30.0);
double sum = 0;
for(double each:cost) {
each += each * 0.05;
sum += each;
}
System.out.println(sum);//63.0
4.filter操作
List cost = Arrays.asList(10.0,20.0,30.0,40.0);
List filteredCost = cost.stream().filter(x -> x >25.0).collect(Collectors.toList());
filteredCost.forEach(x -> System.out.println(x));//30.0 40.0
5.与函数式接口Predicate配合
public static void filterTest(List languages, Predicate condition) {
languages.stream().filter(x -> condition.test(x)).forEach(x -> System.out.println(x + " "));
}
public static void main(String[] args) {
List languages = Arrays.asList("Java","Python","scala","Shell","R"); System.out.println("Language starts with J: ");
filterTest(languages,x -> x.startsWith("J"));
System.out.println("\nLanguage ends with a: ");
filterTest(languages,x -> x.endsWith("a"));
System.out.println("\nAll languages: ");
filterTest(languages,x -> true);
System.out.println("\nNo languages: ");
filterTest(languages,x -> false);
System.out.println("\nLanguage length bigger three: ");
filterTest(languages,x -> x.length() > 4);
}
返回结果:
Language starts with J:
Java
Language ends with a:
Java
scala
All languages:
Java
Python
scala
Shell
R
No languages:
Language length bigger three:
Python
scala
Shell
6.替代匿名内部类
new Thread(new Runnable() {
@Override public void run() {
System.out.println("The old runable now is using!");
}
}).start();
等同于
new Thread(() -> System.out.println("It's a lambda function!")).start();