一、map
通过名字知道这是个映射关系。
1.1、方法定义
<R> Stream<R> map(Function<? super T, ? extends R> mapper);
1.2、英文原意
Returns a stream consisting of the results of applying the given function to the elements of this stream.
把这个流中的元素都经过function的调用,然后把function调用的所有结果再组成一个流。
1.3 代码演示
Stream<String> stream = Stream.of("1","2","3");
Stream<Integer> mapResult = stream.map(str->Integer.parseInt(str));
二、flatMap
扁平化映射,这个从字面理解有点难
2.1、方法定义
<R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper);
- 先理解function的转换结果:? extends Stream<? extends R>,首先 ?是一个流,也就是说function转换结果必须是个流,然后这个流的上边界是 Stream<? extends R>。
- 在理解flatMap返回值
Stream <R>
: 假如 调用者的流有10个元素,经过function后会变成10个流,但是结果却不是一个具有长度为10的流数组,而是成为了一个大的流。 这也就是flatmap叫做合并流的原因
2.2、英文原意
Returns a stream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element
把这个流中的元素都经过function的调用,然后把经过function调用产生的流组成一个流返回
2.3 代码演示
Stream<String> stream = Stream.of("hello","world");
Stream<String> flatMapResult = stream.flatMap(str-> Arrays.stream(str.split("")));
flatResult.forEach(System.out::print);
Stream<String[]> mapResult = stream.map(str->str.split(""));
flatMapResult: h e l l o w o r l d
三、分组
3.3 代码演示
public void testGroup(){
List<User> list = new ArrayList();
list.add(new User(10,"a"));
list.add(new User(11,"b"));
list.add(new User(12,"c"));
list.add(new User(10,"d"));
Map<Integer,List<User>> map = list.stream().collect(Collectors.groupingBy(User::getAge));
map.forEach((age,lists)->{
System.out.println("age:"+age+",group size:"+lists.size());
});
}