JDK1.8之lambda与stream的实际应用

一、lambda和stream的理论知识学习参考链接(写得很全面)

二、实际运用。

package com.lambda;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.BeanUtils;

public class StreamTest {

	/**
	 * 复制对象 -----使用BeanUtils的静态方法
	 */
	@Test
	public void copyObjectTest() {
		Student student = new Student(25);
		Student copyStu = new Student();
		BeanUtils.copyProperties(student, copyStu);
		Assert.assertEquals(25, copyStu.getAge().intValue());
	}

	/**
	 * 传统复制对象集合的方式使用循环
	 */
	@Test
	public void copyOjbectListTest() {
		List<Student> oriList = Arrays.asList(new Student(20), new Student(21), new Student(22));
		List<Student> destList = new ArrayList<>();
		// 循环复制
		for (Student student : oriList) {
			destList.add(student);
		}
		// 循环输出
		for (Student student : destList) {
			System.out.println(student.getAge());
		}
	}

	/**
	 * 使用stream+lambda表达式复制对象并循环输出的方式
	 */
	@Test
	public void copyObjectListByStreamTest() {
		List<Student> oriList = Arrays.asList(new Student(20), new Student(21), new Student(22));
		// 使用lambda表达式+stream复制
		List<Student> destList = oriList.stream().map(s -> new Student(s.getAge())).collect(Collectors.toList());
		// 使用lambda方式输出
		destList.forEach(s -> System.out.println(s.getAge()));
	}
}

class Student {
	private Integer age;

	public Student() {

	}

	public Student(Integer age) {
		super();
		this.age = age;
	}

	public Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}

}
    通过使用可以发现,使用lambda和stream的方式,可以减少很大的代码量,提升开发速度,但是这种方式代码可读性下降,其他开发人员不了解的需要花费时间研究,并且不熟悉时容易产生更多的bug,开发时需要考虑使用。

猜你喜欢

转载自blog.csdn.net/xiaoying0531/article/details/80971060
今日推荐