Java8如何让自己的代码不那么啰嗦?!

2020-03-11  

Java 8 的新特性: Lamdba(匿名函数)、Stream(流)、接口新增了默认方法。

这些改变会让你编程更容易,用不着再写一些啰嗦的代码。

 

1、比如你想在 Java 代码中按水果对象的重量去排序这个集合

/**
 * 水果
 * @author ConstXiong
 * @date 2020-03-11 12:29:02
 */
class Fruit {
	private String type;
	private String color;
	private double weight;
	
	public Fruit(String type, String color, double weight) {
		this.type = type;
		this.color = color;
		this.weight = weight;
	}
	
	public String getColor() {
		return this.color;
	}
	
	public double getWeight() {
		return this.weight;
	}
	
	public String getType() {
		return this.type;
	}

	@Override
	public String toString() {
		return String.format("{type:%s,color:%s,weight:%s}", type, color, weight);
	}
}

在 JDK 8 之前必须这么做

Collections.sort(list, new Comparator<Fruit>() {
	@Override
	public int compare(Fruit o1, Fruit o2) {
		return o1.getWeight() >= o2.getWeight() ? 1 : -1;
	}
});

在 JDK 8 里面,你可以编写更为简洁的代码,这些代码读起来更接近问题的描述(按重量排序水果)

list.sort((Fruit f1, Fruit f2) -> f1.getWeight() >= f2.getWeight() ? 1 : -1);

list.sort(Comparator.comparing(Fruit::getWeight));

 

 

2、获取当前目录下的文件夹

在 JDK 8 之前必须这么做

File[] dirs = new File(".").listFiles(new FileFilter(){
	public boolean accept(File file) {
		return file.isDirectory();
	}
});

在 JDK 8 可以这么写

File[] dirs = new File(".").listFiles(File::isDirectory);

 

3、从水果的集合里获取苹果集合

在 JDK 8 之前必须这么做

List<Fruit> apples = new ArrayList<Fruit>();
for (Fruit fruit : list) {
	if ("苹果".equals(fruit.getType())) {
		apples.add(fruit);
	}
}

在 JDK 8 可以这么写

List<Fruit> apples = list.stream()
				.filter(f -> "苹果".equals(f.getType()))
				.collect(Collectors.toList());

 

 

4、启动一个线程

JDK 8 之前

new Thread(new Runnable() {
	@Override
	public void run() {
	    System.out.println("a thread start");
	}
}).start();

JDK 8 可以这么写

new Thread(() -> System.out.println("a thread start")).start();

 

 

这些都得益于,Java 8 的新特性: Lamdba 表达式(匿名函数)、Stream(流)、接口支持默认方法。

  • Lamdba 表达式:目的是将行为参数化,把函数当成一个参数,传递给方法。让 Java 支持了函数式编程的风格。
  • Stream(流):声明的方式处理集合数据。把集合看作流, 流在管道中传输, 可以在管道的节点上对流数据进行筛选、排序、聚合等操作的处理。
  • 接口支持默认方法:升级了集合的接口支持 Stream API,为了让基于 Java 8 之前版本不报错,接口中添加了 default 关键字修饰默认实现的方法。

 

ConstXiong 备案号:苏ICP备16009629号-3