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: