Java 8 新特性(三)Stream API

一、Stream API

Java 8 API添加了一个新的抽象称为流Stream,可以让你以一种声明的方式处理数据。 

这种风格将要处理的元素集合看作一种流, 流在管道中传输, 并且可以在管道的节点上进行处理, 比如筛选, 排序,聚合等。

元素流在管道中经过中间操作(intermediate operation)的处理,最后由最终操作(terminal operation)得到前面处理的结果。

Java 8 新特性(三)Stream API_第1张图片

生成流

在 Java 8 中, 集合接口有两个方法来生成流:

  • stream() − 为集合创建串行流

  • parallelStream() − 为集合创建并行流

List strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
List filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList());

操作集合的方法 :Collection.stream(); 会返回一个Stream对象,通过这个Stream对象,以流的方式操作集合中的元素 

 

1、filter

Stream filter(Predicate predicate); 

对集合中的元素进行过滤,返回包含符合条件的元素流

Liststrings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
// 获取空字符串的数量
long count = strings.stream().filter(string -> string.isEmpty()).count();

 

2、forEach

void forEach(Consumer action);

遍历集合中的元素

Liststrings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");

strings.stream().forEach(string -> System.out.println(string));
strings.stream().forEach(System.out::println);//是上面的简写方式

 

3、map

Stream map(Function mapper);

map 方法用于映射每个元素到对应的结果

List numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
// 获取对应的平方数
List squaresList = numbers.stream().map( i -> i*i).distinct().collect(Collectors.toList());

案例:先对集合中元素进行操作,再对集合中年龄大于27岁的进行过滤,并遍历集合

		List persons = new ArrayList(){
			{//匿名类初始化参数
				add(new Person("marvin", 18));
				add(new Person("jerry", 31));
				add(new Person("sally", 30));
				add(new Person("max", 27));
				add(new Person("jason", 32));

			}
		};

		persons.stream()
				//年龄大于27岁的对象返回,其他的设置为null
				.map(e ->{
					if(e.getAge()>27){
						return e;
					}
					return null;
				})
				//过滤掉null的数据
				.filter(e -> e!=null)
				//将流转换为list集合
				.collect(Collectors.toList())
				//遍历集合中的对象
				.forEach(System.out::println);

 

 4、limit

Stream limit(long maxSize);

limit 方法用于获取指定数量的流,返回参数maxSize所指定的个数的元素

//以下代码片段使用 limit 方法打印出随机 10 条数据
Random random = new Random();
random.ints().limit(10).forEach(System.out::println);
//获取前三个
List s = Arrays.asList("1","2","3","4","5","6");
s.stream().limit(3).forEach(System.out::println);

 

5、sorted

Stream sorted();

sorted 方法用于对流中的元素自然排序

Stream sorted(Comparator comparator);

根据参数指定的比较规则,对集合中元素排序

List s = Arrays.asList("6","5","3","1","2","1");
s.stream().sorted().forEach(System.out::println);

案例:将集合中对象以年龄倒序排序 

List persons = new ArrayList(){
			{//匿名类初始化参数
				add(new Person("marvin", 18));
				add(new Person("jerry", 31));
				add(new Person("sally", 30));
				add(new Person("max", 27));
				add(new Person("jason", 32));

			}
		};
		persons.stream().sorted(Comparator.comparing(Person::getAge).reversed()).forEach(System.out::println);

 

二、Collectors

Collectors 类实现了很多归约操作,例如将流转换成集合和聚合元素。Collectors 可用于返回列表或字符串:

Liststrings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
List filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList());
 
System.out.println("筛选列表: " + filtered);
String mergedString = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.joining(", "));
System.out.println("合并字符串: " + mergedString);

 

 

Java 8 新特性(三)Stream API_第2张图片

 

练习案例:

案例1:

对persons集合过滤,过滤条件为姓名字符串的长度大于3,接着按照姓名排序,再把集合中前三个Person对象的信息打印出来

	public static void main(String[] args) {
		List persons = new ArrayList(){
			{//匿名类初始化参数
				add(new Person("marvin", 18));
				add(new Person("jerry", 31));
				add(new Person("sally", 30));
				add(new Person("max", 27));
				add(new Person("jason", 32));
				
			}
		};
		
		persons.stream().filter(p->p.getName().length()>3)//姓名字符串长度大于3
		.sorted((p1,p2)->(p1.getName().compareTo(p2.getName())))
		.limit(3)//取出 三个元素
		.forEach(p->System.out.println(p.getName()+":"+p.getAge()));
	}

 

案例2:使用List流排序

package com.stream.demo;
 
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
 
public class StreamListDemo {
	public static void main(String[] args) {
		List list = new ArrayList<>();
		list.add(new Student(1, "Mahesh", 12));
		list.add(new Student(2, "Suresh", 15));
		list.add(new Student(3, "Nilesh", 10));
 
		System.out.println("---Natural Sorting by Name---");
		List slist = list.stream().sorted().collect(Collectors.toList());
		slist.forEach(e -> System.out.println("Id:" + e.getId() + ", Name: " + e.getName() + ", Age:" + e.getAge()));
 
		System.out.println("---Natural Sorting by Name in reverse order---");
		slist = list.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
		slist.forEach(e -> System.out.println("Id:" + e.getId() + ", Name: " + e.getName() + ", Age:" + e.getAge()));
 
		System.out.println("---Sorting using Comparator by Age---");
		slist = list.stream().sorted(Comparator.comparing(Student::getAge)).collect(Collectors.toList());
		slist.forEach(e -> System.out.println("Id:" + e.getId() + ", Name: " + e.getName() + ", Age:" + e.getAge()));
 
		System.out.println("---Sorting using Comparator by Age with reverse order---");
		slist = list.stream().sorted(Comparator.comparing(Student::getAge).reversed()).collect(Collectors.toList());
		slist.forEach(e -> System.out.println("Id:" + e.getId() + ", Name: " + e.getName() + ", Age:" + e.getAge()));
	}
}
package com.stream.demo;
 
public class Student implements Comparable {
	private int id;
	private String name;
	private int age;
 
	public Student(int id, String name, int age) {
		this.id = id;
		this.name = name;
		this.age = age;
	}
 
	public int getId() {
		return id;
	}
 
	public String getName() {
		return name;
	}
 
	public int getAge() {
		return age;
	}
 
	@Override
	public int compareTo(Student ob) {
		return name.compareTo(ob.getName());
	}
 
	@Override
	public boolean equals(final Object obj) {
		if (obj == null) {
			return false;
		}
		final Student std = (Student) obj;
		if (this == std) {
			return true;
		} else {
			return (this.name.equals(std.name) && (this.age == std.age));
		}
	}
 
	@Override
	public int hashCode() {
		int hashno = 7;
		hashno = 13 * hashno + (name == null ? 0 : name.hashCode());
		return hashno;
	}
}

执行结果

---Natural Sorting by Name---
Id:1, Name: Mahesh, Age:12
Id:3, Name: Nilesh, Age:10
Id:2, Name: Suresh, Age:15
---Natural Sorting by Name in reverse order---
Id:2, Name: Suresh, Age:15
Id:3, Name: Nilesh, Age:10
Id:1, Name: Mahesh, Age:12
---Sorting using Comparator by Age---
Id:3, Name: Nilesh, Age:10
Id:1, Name: Mahesh, Age:12
Id:2, Name: Suresh, Age:15
---Sorting using Comparator by Age with reverse order---
Id:2, Name: Suresh, Age:15
Id:1, Name: Mahesh, Age:12
Id:3, Name: Nilesh, Age:10

 

案例3:使用set流排序


package com.stream.demo;
 
import java.util.Comparator;
import java.util.HashSet;
import java.util.Set;
 
public class StreamSetDemo {
	public static void main(String[] args) {
		Set set = new HashSet<>();
		set.add(new Student(1, "Mahesh", 12));
		set.add(new Student(2, "Suresh", 15));
		set.add(new Student(3, "Nilesh", 10));
 
		System.out.println("---Natural Sorting by Name---");
		System.out.println("---Natural Sorting by Name---");
		set.stream().sorted().forEach(e -> System.out.println("Id:"
						+ e.getId() + ", Name: " + e.getName() + ", Age:" + e.getAge()));
 
		System.out.println("---Natural Sorting by Name in reverse order---");
		set.stream().sorted(Comparator.reverseOrder()).forEach(e -> System.out.println("Id:"
						+ e.getId() + ", Name: " + e.getName() + ", Age:" + e.getAge()));
 
		System.out.println("---Sorting using Comparator by Age---");
		set.stream().sorted(Comparator.comparing(Student::getAge))
						.forEach(e -> System.out.println("Id:" + e.getId() + ", Name: " + e.getName() + ", Age:" + e.getAge()));
 
		System.out.println("---Sorting using Comparator by Age in reverse order---");
		set.stream().sorted(Comparator.comparing(Student::getAge).reversed())
						.forEach(e -> System.out.println("Id:" + e.getId() + ", Name: " + e.getName() + ", Age:" + e.getAge()));
	}
}

案例4:使用Map流排序

package com.stream.demo;
 
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
 
public class StreamMapDemo {
	public static void main(String[] args) {
		Map map = new HashMap<>();
		map.put(15, "Mahesh");
		map.put(10, "Suresh");
		map.put(30, "Nilesh");
 
		System.out.println("---Sort by Map Value---");
		map.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getValue))
						.forEach(e -> System.out.println("Key: "+ e.getKey() +", Value: "+ e.getValue()));
 
		System.out.println("---Sort by Map Key---");System.out.println("---Sort by Map Key---");
		map.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getKey))
						.forEach(e -> System.out.println("Key: "+ e.getKey() +", Value: "+ e.getValue()));
	}
}

你可能感兴趣的:(Java,SE)