New Things in Java8

New Things in Java8
1. Functional Interface
 
2. Lambda
public int sum(int x, int y){
     return x + y;
}
 
(int x, int y) -> { return x + y; }
java8 can guess and decide the type
(x, y) -> { return x + y;}
 
The magic part is the comparator class
Comparator comparator = (str1,str2) -> {return s1.compareToIgnoreCase(s2);}
 
3. Function as first-class object
Function<String, String> upperfier = String::toUpperCase;
System.out.println(upperfier.apply(“Hello"));
 
Predicate
Set<String> knowNames = new HashSet<>();
knowNames.add(“sillycat");
knowNames.contains(“sillycat");
 
Predicate<String> isKnowName = knowNames::contains;
isKnowName.test(“sillycat");
 
4. More Static Methods
Public static <T, U extends Comparable<? super U>> Comparator<T> comparing(Function<? super T, ? extends U> keyExtractor){}
 
Compare Name
Comparator nameComparator = Comparator.comparing(Emloyee::getName);
Compare Salary
Comparator salaryComparator = Comparator.comparing(Employee::getSalary);
 
5. Stream
map, filter, reduce
//list sum
int result = list.stream().reduce(0, (x,y) -> x+y);
 
//list filter
int result = list.stream().filter(x -> x > 5).reduce(0, (x,y) -> x+y);
 
//list map
int result = list.stream().filter(x->x>5).map(x->x*x).mapToInt(x->x).sum();
 
Really Nice
//salary sum
int totalSalary = employees.stream().map(e->e.getSalary()).reduce(0,(x,y)->x+y);
 
double averageSalary = employees.stream().mapToInt(e->e.getSalary()).average().getAsDouble();
 
Just read these 2 blogs, java8 really contains a lot of nice things. Need to read the book when I begin to use a lot of that.
 
References:
 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值