1. 程式人生 > >java8 Stream的基本操作

java8 Stream的基本操作

JAVA8的流式操作
1)1篩選和切片
* filter : 對資料進行過濾
* limit:截斷流,使其結果不超過給定的數量
* split ,跳過給定的n個元素,若流中不足n個元素,則返回一個空流 ,與limit(n)互補
* distinct 根據hashCode和equals對流中的元素去重

 public class StreamTest {
	List<Employee> emps = Arrays.asList(new Employee("張三",38,8888.88),
									new Employee("李四",33,6666.66),
									new Employee("王五",40,9999.99),
									new Employee("趙六",25,19999.88),
									new Employee("田七",36,18888.88),
									new Employee("田七",36,18888.88),
									new Employee("田七",36,18888.88)
									);
	/**
	 * 1: 篩選和切片
	 * filter :  對資料進行過濾
	 * limit:截斷流,使其結果不超過給定的數量
	 * split ,跳過給定的n個元素,若流中不足n個元素,則返回一個空流 ,與limit(n)互補
	 * distinct 根據hashCode和equals對流中的元素去重
	 */
	@Test
	public void testFilter(){
		emps.stream()
			.filter((emp) -> emp.getAge()>30)
			.forEach(System.out::println);
	}
	
	@Test
	public void testLimt(){
		emps.stream()
			.filter((emp) -> emp.getAge()>35)
			.limit(2)
			.forEach(System.out::println);
	}
	
	@Test
	public void testSkip(){
		emps.stream()
			.filter((emp) -> emp.getAge()>35)
			.skip(2)
			.forEach(System.out::println);
	}
	
	@Test
	public void testDistinct(){
		emps.stream()
			.filter((emp) -> emp.getAge()>35)
			.distinct()
			.forEach(System.out::println);
	}
	
}