Java8新特性
Project 01
- 给出了行为参数化传递代码的方式
- 定义一个标准的谓词模板
public interface ApplePredicate{
boolean test (Apple apple);
}
- 用ApplePredicate的多个实现代表不同的选择标准
public class AppleHeavyWeightPredicate implements ApplePredicate{
public boolean test(Apple apple){
return apple.getWeight() > 150;
}
}
public class AppleGreenColorPredicate implements ApplePredicate{
public boolean test(Apple apple){
return "green".equals(apple.getColor());
}
}
- 设置抽象条件筛选
public static List filterApples(List inventory,ApplePredicate p){
List result = new ArrayList<>();
for(Apple apple: inventory){
if(p.test(apple)){
result.add(apple);
}
}
return result;
}
- 代码传递行为
public class AppleRedAndHeavyPredicate implements ApplePredicate{
public boolean test(Apple apple){
return "red".equals(apple.getColor()) && apple.getWeight() > 150;
}
}
List redAndHeavyApples = filterApples(inventory, new AppleRedAndHeavyPredicate());
- 使用匿名类
List redApples = filterApples(inventory, new ApplePredicate() {
public boolean test(Apple apple){
return "red".equals(apple.getColor());
});
}
- 使用Lambda表达式
List result = filterApples(inventory, (Apple apple) -> "red".equals(apple.getColor()));
- 将List抽象化
public interface Predicate{
boolean test(T t);
}
public static List filter(List list, Predicate p){
List result = new ArrayList<>();
for(T e: list){
if(p.test(e)){
result.add(e);
}
}
return result;
}
Project 02
匿名类与Lambda表达式的使用
使用函数式接口
- java.util.function.Predicate
接口定义了一个名叫test的抽象方法,它接受泛型 T对象,并返回一个boolean
@FunctionalInterface
public interface Predicate{
boolean test(T t);
}
public static List filter(List list, Predicate p) {
List results = new ArrayList<>();
for(T s: list){
if(p.test(s)){
results.add(s);
}
}
return results;
}
Predicate nonEmptyStringPredicate = (String s) -> !s.isEmpty(); List nonEmpty = filter(listOfStrings, nonEmptyStringPredicate);
- java.util.function.Consumer
定义了一个名叫accept的抽象方法,它接受泛型T的对象,没有返回(void)。你如果需要访问类型T的对象,并对其执行某些操作,就可以使用这个接口。
@FunctionalInterface
public interface Consumer{
void accept(T t);
}
public static void forEach(List list, Consumer c){
for(T i: list){
c.accept(i);
}
}
forEach(Arrays.asList(1,2,3,4,5), (Integer i) -> System.out.println(i));
- java.util.function.Function
接口定义了一个叫作apply的方法,它接受一个泛型T的对象,并返回一个泛型R的对象。如果你需要定义一个Lambda,将输入对象的信息映射到输出,就可以使用这个接口。
@FunctionalInterface
public interface Function{
R apply(T t);
}
public static List map(List list, Function f) {
List result = new ArrayList<>();
for(T s: list){
result.add(f.apply(s));
}
return result;
}
List l = map(Arrays.asList("lambdas","in","action"), (String s) -> s.length());
Project 03
- 引入流Stream
List heavyApples = inventory.stream().filter((Apple a) -> a.getWeight() > 150).collect(toList());
- 如何使用Stream
- 如何用流收集数据
- 并行数据处理
List heavyApples = inventory.parallelStream().filter((Apple a) -> a.getWeight() > 150) .collect(toList());
Project 04
- 使用Java8新特性重构代码
- Optional
- CompletableFuture
源码参考
Java8InAction