JDK8新特性stream的简单使用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lx_nhs/article/details/88389427

一. 介绍

此处的stream和io包下的stream完全是两个概念, Java 8 中的 Stream 是对集合(Collection)对象功能的增强,它专注于对集合对象进行各种非常便利、高效的聚合操作(aggregate operation),或者大批量数据操作 (bulk data operation)。

二. 特点

1.stream本身并不存储数据,数据是存储在对应的collection里,或者在需要的时候才生成的; 
2.stream不会修改数据源,总是返回新的stream; 
3.stream的操作是懒执行(lazy)的:仅当最终的结果需要的时候才会执行;

三. 使用

1. 数据准备:

People.class:

public class People {
	private String name;
	private Integer age;
	
	public People() {
	}
	
	public People(String name, Integer age) {
		this.name = name;
		this.age = age;
	}
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	
	@Override
	public String toString() {
		return "[name:"+this.name+", age:"+this.age+"]";
	}
}

2. 使用stream

package stream;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.junit.Test;

import com.google.gson.Gson;

import entity.People;

public class StreamTest {
	
    // 数据准备
	@SuppressWarnings("serial")
	private List<String> colorList = new ArrayList<String>() {
		{
			add("red");
			add("blue");
			add("black");
			add("green");
			add("blue");
		}
	};
	
    // 数据准备
	@SuppressWarnings("serial")
	private List<People> peopleList = new ArrayList<People>() {
		{
			add(new People("张三", 10));
			add(new People("李四", 20));
			add(new People("王五", 30));
			add(new People("赵六", 40));
		}
	};
	
	// 案例1: 创建stream
	@Test
	public void demo1_createStream() {
		// 方式1:
		Stream.of(colorList).forEach(System.out::println);
		// 方式2:
		peopleList.stream().forEach(System.out::println);
	}
	
	// 案例2: filter过滤操作
	@Test
	public void demo2_filter() {
		// 过滤掉以'b'字母开头的字母
		colorList.stream().filter(color -> !color.startsWith("b")).forEach(System.out::println);
		// 输出: red green
	}
	
	// 案例3: map
	@Test
	public void demo3_map() {
		// 1.打印出peopleList中的姓名
		peopleList.stream().map(p -> p.getName()).forEach(name -> System.out.println(name));
		// 输出: 张三  李四  王五  赵六
		// 2.将peopleList中的姓名转化为一个新的集合, collect用法稍后介绍
		List<String> nameList = peopleList.stream().map(p -> p.getName()).collect(Collectors.toList());		
		nameList.forEach(System.out::println);
		// 输出: 张三  李四  王五  赵六
	}
	
	// 案例4: distinct去重
	@Test
	public void demo4_distinct() {
		// 对colorList进行去重
		colorList.stream().distinct().forEach(color -> System.out.println(color));
		// 输出: red  blue  black  green
	}
	
	// 案例5: sorted排序
	@Test
	public void demo5_sorted() {
		// 对peopleList中的人员按年龄从大到小排序
		peopleList.stream().sorted(new Comparator<People>() {
			@Override
			public int compare(People p1, People p2) {
				return p2.getAge()-p1.getAge();
			}
		}).forEach(System.out::println);
		/**
		 * 输出:
		 * [name:赵六, age:40]
		 * [name:王五, age:30]
		 * [name:李四, age:20]
		 * [name:张三, age:10]
		 */
	}
	
	// 案例6: collect结果转化
	@Test
	public void demo6_collect() {
		// 1. 将colorList去重并且按首字母从大到小排序并输出为Set集合
		Set<String> sortedSet = colorList.stream().distinct().sorted(new Comparator<String>() {
			@Override
			public int compare(String color1, String color2) {
				return color2.compareTo(color1);
			}
		}).collect(Collectors.toSet());
		sortedSet.forEach(color -> System.out.print(color+"  "));
		// 输出: red  green  blue  black  
		
		// 2. 将peopleList转化为以姓名为key的map, 值为people元素本身
		Map<String, People> peopleMap = peopleList.stream().collect(Collectors.toMap(People::getName, Function.identity()));
		Gson gson = new Gson();
		System.out.println(gson.toJson(peopleMap));
		// 输出: {"李四":{"name":"李四","age":20},"张三":{"name":"张三","age":10},"王五":{"name":"王五","age":30},"赵六":{"name":"赵六","age":40}}
	}
}

 

猜你喜欢

转载自blog.csdn.net/lx_nhs/article/details/88389427
今日推荐