首先我们来看一下具体的实例:
List<String> t = new ArrayList();
t.add("01A");
t.add("02D");
t.add("03C");
t.add("01A");
List<String>filleNames = t.stream().map(s -> { return s.toLowerCase();}).collect(Collectors.toList());
for(int t1=0;t1<filleNames.size(); t1++)
{
System.out.println(filleNames.get(t1));
}
输出结果:
对于上面的代码,解释为:
1.首先对于数组t,对于数组t中的每一个元素做一下的操作;
2.对于每一个元素吧大写字母变成小写字母;
3.返回一个list对象;
4.遍历list对象输出。
上面的代码还可以替换成下面的lambda的表达式:
t.stream().forEach((s)->{System.out.println(s.toLowerCase());});
结果如下:
输出结果一样的。
如果还不明白可以看 可以分析一下lambda表达式在干嘛
(1)首先对于某一个具体的语法,我们按照惯例开始阅读API;
对于stream的API解释如下:
Stream<String> java.util.Collection.stream()
Returns a sequential Stream
with this collection as its source.
This method should be overridden when the spliterator()
method cannot return a spliterator that is IMMUTABLE
, CONCURRENT
, or late-binding. (See spliterator()
for details.)
Returns:
a sequential Stream
over the elements in this collection
返回一个元素输出流;
map的API解释如下:
<String> Stream<String> java.util.stream.Stream.map(Function<? super String, ? extends String> mapper)
Returns a stream consisting of the results of applying the given function to the elements of this stream
返回一个流,这个流会处理每一个给定的元素
tolist()的API解释如下:
<String> Collector<String, ?, List<String>> java.util.stream.Collectors.toList()
Returns a Collector
that accumulates the input elements into a new List
. There are no guarantees on the type, mutability, serializability, or thread-safety of the List
returned; if more control over the returned List
is required, use toCollection(Supplier)
.
对于每一个输入的元素进行 list存贮,然后返回。
综合上面的例子可以看出:forEach与Collectors有类似的作用。