例1、用lambda表达式实现Runnable
@Test
public void exam1(){
// Java 8之前:
{
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("Before Java8, too much code for too little to do");
}
}).start();
}
//Java 8方式:
{
new Thread( () -> System.out.println("In Java8, Lambda expression rocks !!")).start();
}
}
console
Before Java8, too much code for too little to do
In Java8, Lambda expression rocks !!
例3、使用lambda表达式对列表进行迭代
@Test
public void exam3(){
// Java 8之前:
{
List<String> list = Arrays.asList("aaa", "bbb", "ccc", "ddd");
for(String s : list){
System.out.println(s);
}
}
// Java 8之后:
{
List<String> list = Arrays.asList("aaa", "bbb", "ccc", "ddd");
list.forEach(e -> System.out.println(e));
//使用[方法引用]后:
list.forEach(System.out::println);
}
}
console
Java 8之前
aaa
bbb
ccc
ddd
Java 8之后
aaa
bbb
ccc
ddd
aaa
bbb
ccc
ddd
例4、使用lambda表达式和函数式接口Predicate(谓词/断言)
@Test
public void exam4(){
List<String> languages = Arrays.asList("Java", "Scala", "C++", "Haskell", "Lisp");
Consumer<String> printString = str -> System.out.println("\t" + str);
System.out.println("Languages which starts with 'J' :");
// filter(languages, (str)->((String)str).startsWith("J"));
languages.stream().filter(str->str.startsWith("J")).forEach(printString);
System.out.println("Languages which ends with 'a' ");
filter(languages, (str)->((String)str).endsWith("a"));
// languages.stream().filter(str -> str.endsWith("a")).forEach(printString);
System.out.println("Print all languages :");
// filter(languages, (str)->true);
languages.stream().filter(str -> true).forEach(printString);
System.out.println("Print no language : ");
// filter(languages, (str)->false);
languages.stream().filter(str -> false).forEach(printString);
System.out.println("Print language whose length greater than 4:");
// filter(languages, (str)->((String)str).length() > 4);
languages.stream().filter(str -> str.length() > 4).forEach(printString);
}
//演示
private static void filter(List<String> names, Predicate condition) {
// for(String name: names) {
// if(condition.test(name)) {
// System.out.println("\t" + name);
// }
// }
//更好的办法------filter过滤掉不需要的元素流,返回符合条件的元素流
names.stream()
.filter((name) -> (condition.test(name)))
.forEach((name) -> System.out.println("\t" + name) );
}
console
Languages which starts with 'J' :
Java
Languages which ends with 'a'
Java
Scala
Print all languages :
Java
Scala
C++
Haskell
Lisp
Print no language :
Print language whose length greater than 4:
Scala
Haskell
例5、如何在lambda表达式中加入嵌套Predicate(or,and,xor)
@Test
public void exam5(){
List<String> languages = Arrays.asList("Java", "Scala", "C++", "Haskell", "Lisp", "Jsp");
Predicate<String> startWithJ = str -> str.startsWith("J");
Predicate<String> fourLetterLong = str -> str.length() == 4;
languages.stream()
.filter(startWithJ.and(fourLetterLong))
.forEach( e -> System.out.println(e));
}
console
Java
例6、Java 8中使用lambda表达式的Map和Reduce示例
@Test
public void exam6(){
List<Integer> costBeforeTax = Arrays.asList(100, 200, 300, 400, 500);
//map操作
{
// 不使用lambda表达式为每个订单加上12%的税
for (Integer cost : costBeforeTax) {
double price = cost + .12*cost;
System.out.println(price);
}
//map: 流元素 ----lambda表达式-----> 新的流元素组成的流
costBeforeTax.stream()
.map(cost -> cost + .12*cost)
.forEach(System.out::println);
}
/*reduce操作, reduce() 函数可以将所有值合并成一个。
过程说明,例如对于流{e1,e2,e3,e4},reduce((n1, n2) -> n1 + n2)的过程如下:
1:(e1, e2),返回a=e1+e2
2:(a, e3) 返回b=a+e3
3:(c, e4) 返回d=c+e4
结束。
*/
{
// 为每个订单加上12%的税
double total = 0;
for (Integer cost : costBeforeTax) {
double price = cost + .12*cost;
total = total + price;
}
System.out.println("Total : " + total);
// 新方法:
double bill = costBeforeTax.stream()
.map((cost) -> cost + .12*cost)
.reduce((sum, cost) -> sum + cost)
// .reduce((sum, cost) -> {System.out.println("sum=" + sum + ", cost=" + cost); return sum + cost; })
.get();
System.out.println("Total : " + bill);
}
}
console
112.0
224.0
336.0
448.0
560.0
112.0
224.0
336.0
448.0
560.0
Total : 1680.0
Total : 1680.0
例7、通过过滤创建一个String列表
@Test
public void exam7(){
// 创建一个字符串列表,每个字符串长度大于2
List<String> strList = Arrays.asList("hello", ",i", "'am", "Geliang");
List<String> filtered = strList.stream()
.filter(x -> x.length()> 2)
.collect(Collectors.toList());
System.out.printf("Original List : %s, filtered list : %s \n", strList, filtered);
}
console
Original List : [hello, ,i, 'am, Geliang], filtered list : [hello, 'am, Geliang]
例8、对列表的每个元素应用函数
@Test
public void exam8(){
// 将字符串换成大写并用逗号链接起来
List<String> G7 = Arrays.asList("USA", "Japan", "France", "Germany", "Italy", "U.K.","Canada");
String G7Countries = G7.stream()
.map(x -> x.toUpperCase())
.collect(Collectors.joining(", "));
System.out.println(G7Countries);
}
console
USA, JAPAN, FRANCE, GERMANY, ITALY, U.K., CANADA
例9、复制不同的值,创建一个子列表
@Test
public void exam9(){
//使用流的distinct方法去除重复的元素
List<Integer> numbers = Arrays.asList(9, 10, 3, 4, 7, 3, 4);
List<Integer> distinct = numbers.stream().map( i -> i*i).distinct().collect(Collectors.toList());
System.out.printf("Original List : %s, Square Without duplicates : %s \n", numbers, distinct);
}
console
Original List : [9, 10, 3, 4, 7, 3, 4], Square Without duplicates : [81, 100, 9, 16, 49]
例10、计算集合元素的最大值、最小值、总和以及平均值
@Test
public void exam10(){
//summaryStatistics() --- 返回一个IntSummaryStatistics描述有关此流元素的各种摘要数据
//获取数字的个数、最小值、最大值、总和以及平均值
List<Integer> primes = Arrays.asList(2, 3, 5, 7, 11, 13, 17, 19, 23, 29);
IntSummaryStatistics stats = primes.stream().mapToInt((x) -> x).summaryStatistics();
System.out.println("Highest prime number in List : " + stats.getMax());
System.out.println("Lowest prime number in List : " + stats.getMin());
System.out.println("Sum of all prime numbers : " + stats.getSum());
System.out.println("Average of all prime numbers : " + stats.getAverage());
}
console
Highest prime number in List : 29
Lowest prime number in List : 2
Sum of all prime numbers : 129
Average of all prime numbers : 12.9