1.使用() -> {} 替代匿名类
(params) -> expression
(params) -> statement
(params) -> { statements }
没带大括号的时候,默认返回expression或statement的值,即 return expression or statement。反之,如果有大括号的时候,同时方法必须有返回值的时候,就需要带return
new Thread( () -> System.out.println("In Java8!") ).start();
new ArrayList().sort((o1,o2)->o1==null?1:-1);
new ArrayList().sort((o1,o2)->{
if(o1==null)
return 1;
else
return 0;
});
2.使用Lambda表达式遍历List集合
new ArrayList().forEach(n -> System.out.println(n));
// Even better use Method reference feature of Java 8
// method reference is denoted by :: (double colon) operator
// looks similar to score resolution operator of C++
new ArrayList().forEach(System.out::println);
//多个入参
new ArrayList().sort(Lambda::testDoubleColon);
3.使用Lambda表达式和函数接口
List<String> languages = Arrays.asList("Java", "Scala", "C++", "Haskell", "Lisp");
//带J的字符串
System.out.println("Languages which starts with J :");
filter(languages, (str)->str.startsWith("J"));
//以a结束
System.out.println("Languages which ends with a ");
filter(languages, (str)->str.endsWith("a"));
//返回true
System.out.println("Print all languages :");
filter(languages, (str)->true);
//返回false
System.out.println("Print no language : ");
filter(languages, (str)->false);
//字符串长度大于4
System.out.println("Print language whose length greater than 4:");
filter(languages, (str)->str.length() > 4);
filter方法
public static void filter(List<String> names, Predicate<String> condition) {
for(String name: names) {
if(condition.test(name)) {
System.out.println(name + " ");
}
}
}
Predicate提供and(), or() 和 xor()可以进行逻辑操作
List<String> languages = Arrays.asList("Java", "Scala", "C++", "Haskell", "Lisp");
Predicate<String> startsWithJ = (n) -> n.startsWith("J");
Predicate<String> fourLetterLong = (n) -> n.length() == 4;
//startsWithJ.and(fourLetterLong) 与操作
languages.stream().filter(startsWithJ.and(fourLetterLong))
.forEach((n) -> System.out.print("\nName, which starts with 'J' and four letter long is : " + n));
4.使用Lambda实现Map 和 Reduce
- stream函数中的map,允许你重新构造新的对象集合
reduce(result,element) 函数是将集合中所有值结合进一个,类似SQL语句中的sum(), avg() 或count()
List<Integer> costBeforeTax = Arrays.asList(100, 200, 300, 400, 500);
double total = 0;
for (Integer cost : costBeforeTax) {
double price = cost + .12*cost;
total = total + price;
}
System.out.println("Total : " + total);
// New way:
double bill = costBeforeTax.stream()
.map((cost) -> cost + .12*cost)
.reduce((result, cost) -> result + cost)
.get();
System.out.println("Total : " + bill);
5. Filter 函数
- Filtering是对大型Collection操作的一个通用操作,Stream提供filter()方法,接受一个Predicate对象,意味着你能传送lambda表达式作为一个过滤逻辑进入这个方法filter 过滤
List<String> languages = Arrays.asList("Java", "Scala", "C++", "Haskell", "Lisp");
List<String> filtered = languages.stream()
.filter(x -> x.length()> 4)
.collect(Collectors.toList());
System.out.printf("Original List : %s, filtered list : %s %n", languages, filtered);
6. Collect 函数
- 将stream对象反构造成list或者map
List<String> languages = Arrays.asList("Java", "Scala", "C++", "Haskell", "Lisp");
String languagesString = languages.stream()
.map(x -> x.toUpperCase())
.collect(Collectors.joining(", "));
System.out.println(languagesString);
7. 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);
8. IntSummaryStatistics 对象
- 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());
网友评论