Stream流的收集操作 对数据使用Stream流的方式操作完毕后,把流中的数据收集到集合中的收集方法: R collect(Collector collector) 这个收集方法的参数就是一个Collector接口 工具类Collector提供具体的收集方式 public static<T> Collector toList(): 把元素收集到List集合中 public static<T> Collector toSet(): 把元素收集到Set集合中 public static Collector to Map(Function keyMapper,Function valueMapper):把元素收集到Map集合中
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class StreamCollector {
public static void main(String[] args) {
//创建List集合对象
List<String> list = new ArrayList<String>();
list.add("林青霞");
list.add("张曼玉");
list.add("王祖贤");
list.add("柳岩");
list.add("王剑波");
//得到名字为3个字的流
Stream<String> liststream = list.stream().filter(s -> s.length() == 3);
//把使用Stream流操作完毕的数据收集到List集合中并遍历
List<String> names = liststream.collect(Collectors.toList());
for(String name : names){
System.out.println(name);
}
//创建Set集合对象
Set<Integer> set = new HashSet<Integer>();
set.add(10);
set.add(25);
set.add(35);
set.add(62);
set.add(66);
set.add(45);
//得到年龄大于25的流
Stream<Integer> setStream = set.stream().filter(age -> age > 25);
//把使用Stream流操作完毕的数据收集到Set集合中并遍历
Set<Integer> ages = setStream.collect(Collectors.toSet());
for(Integer age : ages){
System.out.println(age);
}
//定义一个字符串数组,每一个字符串数据由姓名数据和年龄数据组合而成
String[] strArray = {"林青霞,30","张曼玉,35","王剑波,23","柳岩,25"};
//得到字符串中年龄数据大于28的流
Stream<String> arrayStream = Stream.of(strArray).filter(s -> Integer.parseInt(s.split(",")[1])>28);
//把使用Stream流操作完毕的数据收集到Map集合中并遍历,字符串中的姓名作为键,年龄作为值
Map<String, Integer> map = arrayStream.collect(Collectors.toMap(s -> s.split(",")[0], s -> Integer.parseInt(s.split(",")[1])));
//遍历map集合
Set<String> keySet = map.keySet();
for(String key: keySet){
Integer value = map.get(key);
System.out.println(key+","+value);
}
}
}
作为学习笔记,来自黑马程序员