Stream
不是java
io
中的stream
对象创建
我们没有必要使用一个迭代来创建对象,直接使用流就可以
String[] strs = {"haha","hoho","lala"};
List<String> names = Arrays.asList(strs);
Stream<Person>stream = names.stream().map(Person::new);
List<Person> personList = stream.collect(Collectors.toList());
流使用起来代码更清晰
long count = personList.stream().filter(p->p.getName().length()>10).count();
流看上去有点像是集合,转换或者获取数据,不过有一定的差异性
- 流不会存储元素,,这些元素可能是 储存在底层的集合中,或者按需生成的
- 流的操作不会修改其数据源 比如filter会生成一个新的流
- 流的操作尽可能是惰性执行的
创建:可以使用Collection接口的stream方法
也可以使用静态方法Stream.of()
Stream<String>namesStream = Stream.of("haha","hoho","lala");
无限流
因为流的操作尽可能是惰性的,我们因此可以操作无限流
Stream <T> stream<T> generate(Supplier<T> s)
如果我们希望得到一个新的流,并且需要前n个元素,我们就可以使用 limit方法
namesStream.limit(2);
丢弃前几个元素
namesStream.skip(2)
流之间的连接
Stream.concat(stream1,stream2);
去重复
namesStream.distinct();
甚至还提供了排序接口
namesStream.sorted((s1,s2)->{return s1.length()-s2->length()});
甚至在使用的时候帮助自己调试
Stream.iterate(1.0,p->p*2).peek(e->System.out.println("Fetching"+e)).limit(20).toArray();
terminal 操作
max,min
等等
Optional<T> max(Comparator<? super T>comparator)
返回的Optional有点类似于 C++ Boost中的optional,用于判断返回的结果是否有效
结果返回
stream.collect(Collectors.toList());
stream.collect(Collectors.toSet());
// 也有使用 toJoinning(", ")
//foreach
stream.forEach(System.out::println);
//如果需要转化字符串
stream.map(Object::toString);
收集到映射表中
//
Map<Integer,String> idToName = people.collect(
Collectors.toMap(Person::getId,Person::getName)
);
Map<Integer,Person> idToPerson = people.collect(
Collectors.toMap(Person::getId,Function.identity())
);
groupBy
//举一个java core中的例子
Map<String,List<Locale>>countryToLocales = locales.collect(
Collectors.groupingBy(Locale::getCountry));
下游收集器
Map<String,List<Locale>>countryToLocales = locales.collect(
Collectors.groupingBy(Locale::getCountry,toSet()));