- 函数式编程
- 流
- Optional类
- 日期时间API
- Base64
一、函数式编程
函数式编程的基本理论不再讲述,说一下个人的理解,函数式编程的直接好处是代码层次的复用与抽象,使代码更简洁,复用度更高
以下实例完成一下对象的数据比较过程,对比非函数化编程与函数化编程的优缺点,期望对大家有所帮助。以下是对苹果重量进行排序的过程
1、创建一个Apple实体类:
public class Apple {
private Integer weight; //重量
private String color; //颜色
public Apple(Integer weight, String color) {
this.weight = weight;
this.color = color;
}
public Integer getWeight() {
return weight;
}
public void setWeight(Integer weight) {
this.weight = weight;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
@Override
public String toString() {
return "Apple{" +
"weight=" + weight +
", color='" + color + '\'' +
'}';
}
}
2、JAVA7中的实现:
@Test
public void testJava7() {
//创建苹果列表
List<Apple> appleList = Arrays.asList(
new Apple(36, "green")
, new Apple(45, "red")
, new Apple(89, "orange")
, new Apple(102, "red")
, new Apple(39, "green")
);
//排序前
System.out.println(appleList);
//排序
appleList.sort(new Comparator<Apple>() {
@Override
public int compare(Apple o1, Apple o2) {
return o1.getWeight().compareTo(o2.getWeight());
}
});
//排序后
System.out.println(appleList);
}
3、JAVA8中实现排序
@Test
public void testJava8() {
List<Apple> appleList = Arrays.asList(
new Apple(36, "green")
, new Apple(45, "red")
, new Apple(89, "orange")
, new Apple(102, "red")
, new Apple(39, "green")
);
//排序前
System.out.println(appleList);
appleList.sort(Comparator.comparing(Apple::getWeight));
//排序后
System.out.println(appleList);
}
// todo 20190729 未完待更.................
网友评论