java8中Stream的使用示例教程
Stream是Java8的一大亮点,是对容器对象功能的增强,下面这篇文章主要给大家介绍了关于java8中Stream使用的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来前言
java8中提供了stream对集合操作作出了极大的简化,学习了stream之后,我们以后不用使用for循环就能对集合作出很好的操作。
本文将给大家详细介绍关于java8 stream使用的相关内容,下面话不多说了,来一起看看详细的介绍吧
1. 原理
stream 不是集合元素,它不是数据结构并不保存数据,它是有关算法和计算的,它更像一个高级版本的 iterator。
原始版本的 iterator,用户只能显式地一个一个遍历元素并对其执行某些操作;
高级版本的 stream,用户只要给出需要对其包含的元素执行什么操作,比如:
[*]所有元素求和
[*]过滤掉长度大于 10 的字符串
[*]获取每个字符串的首字母
stream 就如同一个迭代器(iterator),单向,不可往复,数据只能遍历一次,遍历过一次后即用尽了,就好比流水从面前流过,一去不复返。
而和迭代器又不同的是,stream 可以并行化操作
stream 的另外一大特点是,数据源本身可以是无限的
2.使用步骤
获取一个数据源(source)→ 数据转换→执行操作获取想要的结果
每次转换原有 stream 对象不改变,返回一个新的 stream对象(可以有多次转换),这就允许对其操作可以像链条一样排列,变成一个管道,如下图所示。
3. stream的构造
public void test4() {
stream stream = stream.of("a", "b", "c", 23);
stream.foreach(key -> system.out.println(key));
string[] array = new string[]{"abc", "efg"};
stream = stream.of(array);
stream = arrays.stream(array);
stream.foreach(key -> system.out.println(key));
list<string> list = arrays.aslist(array);
stream = list.stream();
//intstream、longstream、doublestream
intstream stream2 = intstream.of(1, 2, 3, 3);
doublestream stream4 = doublestream.of(1, 2, 3, 3.4);
stream2.foreach(key -> system.out.println(key));
stream4.foreach(key -> system.out.println(key));
}
结果
a
b
c
23
abc
efg
1
2
3
3
1.0
2.0
3.0
4. stream的转换
public void test6() {
stream stream = stream.of("abc", "def");
string[] array = (string[])stream.toarray(string[]::new);
system.out.println(array.length);
list<string> list = (list<string>)stream.of("1", "2", "3").collect(collectors.tolist());
string str = stream.of("abc", "mn").collect(collectors.joining()).tostring();
system.out.println(array);
system.out.println(list);
system.out.println(str);
}
结果
2
[ljava.lang.string;@17f052a3
abcmn
5.一个 stream 只可以使用一次
public void test6_5() {
stream stream = stream.of(1, 2, 3, 2);
system.out.println("count:" + stream.count());
system.out.println("count:" + stream.count());
}
输出
exception in thread "main" java.lang.illegalstateexception: stream has already been operated upon or closed
at java.util.stream.abstractpipeline.<init>(abstractpipeline.java:203)
at java.util.stream.longpipeline.<init>(longpipeline.java:91)
at java.util.stream.longpipeline$statelessop.<init>(longpipeline.java:572)
at java.util.stream.referencepipeline$5.<init>(referencepipeline.java:221)
at java.util.stream.referencepipeline.maptolong(referencepipeline.java:220)
at java.util.stream.referencepipeline.count(referencepipeline.java:526)
at streamtest.streamtest.test6_5(streamtest.java:68)
at streamtest.streamtest.main(streamtest.java:181)
count:4
6.转换大写
public void test7() {
list<string> list = arrays.aslist("a", "mnm");
list<string> result = list.stream().
map(string::touppercase).
collect(collectors.tolist());
system.out.println(list);
system.out.println(result);
}
输出
7.平方
public void test8() {
list<integer> list2 = arrays.aslist(1, 2, 4);
list<integer> list3 = list2.stream().
map(key -> key * key).
collect(collectors.tolist());
system.out.println(list2);
system.out.println(list3);
}
输出
8.找偶数
public void test8_5() {
list<integer> list2 = arrays.aslist(1, 2, 4);
list<integer> list3 = list2.stream().
filter(key -> key % 2 == 0).
collect(collectors.tolist());
system.out.println(list2);
system.out.println(list3);
}
输出
9. 区间值
public void test5() {
system.out.println("\n");
intstream.range(1, 3).foreach(system.out::println);
system.out.println("\n");
intstream.rangeclosed(1, 3).foreach(system.out::println);
}
结果
1
2
1
2
3
10.并发
public void test5_pa() {
intstream.rangeclosed(1, 10).parallel().foreach(system.out::println);
}
输出
3
7
1
5
2
8
10
6
9
4
是否并发思考
11. 新的stream继续操作
public void test6_6() {
stream.of("one", "two", "three", "four")
.filter(e -> e.length() > 3)
.peek(e -> system.out.println("filtered value: " + e))
.map(string::touppercase)
.peek(e -> system.out.println("mapped value: " + e))
.collect(collectors.tolist());
}
结果
filtered value: three
mapped value: three
filtered value: four
mapped value: four
12. optional
public static void print(string text) {
system.out.println("<<<<<<");
system.out.println(optional.ofnullable(text));
list<string> obj = new arraylist<>();
optional.ofnullable(text).ifpresent(system.out::println);
system.out.println(">>>>>>>>>>>>\n");
}
public static int getlength(string text) {
return optional.ofnullable(text).map(string::length).orelse(-1);
}
public void test14() {
string stra = " abcd ", strb = null;
print(stra);
print("");
print(strb);
system.out.println(getlength(stra));
system.out.println(getlength(""));
system.out.println(getlength(strb));
}
结果
<<<<<<
optional[ abcd ]
abcd
>>>>>>>>>>>>
<<<<<<
optional[]
>>>>>>>>>>>>
<<<<<<
optional.empty
>>>>>>>>>>>>
6
0
-1
13. 字符串拼接、最值、求和、过滤
public void test15() {
string concat = stream.of("a", "b", "c").reduce("", string::concat);
system.out.println("concat:" + concat);
double minvalue = stream.of(-1.5, 1.0, -3.0, -2.0).reduce(double.max_value, double::min);
system.out.println("min:" + minvalue);
int sumvalue = stream.of(1, 2, 3, 4).reduce(0, integer::sum);
system.out.println("sum1:" + sumvalue);
int sumvalue2 = stream.of(1, 2, 3, 4).reduce(integer::sum).get();
system.out.println("sum2:" + sumvalue2);
concat = stream.of("a", "b", "c", "d", "e", "f").filter(x -> x.compareto("z") > 0).reduce("", string::concat);
system.out.println("concat:" + concat);
}
结果
concat:abc
min:-3.0
sum1:10
sum2:10
concat:ace
14. limit, skip
public void test16() {
list<person> persons = new arraylist<>();
intstream.range(1, 1000).foreach(key->persons.add(new person(key, "jihite:" + key)));
list<string> personlist = persons.stream().map(person::getname).limit(10).skip(3).collect(collectors.tolist());
system.out.println(personlist);
}
输出
15.找出最长一行的长度
public void test19() throws ioexception {
string path = "**/person.java";
bufferedreader br = new bufferedreader(new filereader(path));
int longest = br.lines()
.maptoint(string::length)
.max()
.getasint();
br.close();
system.out.println(longest);
}
输出
16.找出全文的单词,转小写,并排序
public void test20() throws ioexception {
string path = "**/person.java";
bufferedreader br = new bufferedreader(new filereader(path));
list<string> words = br.lines()
.flatmap(line->stream.of(line.split(" ")))
.filter(word->word.length()>0)
.map(string::tolowercase)
.distinct()
.sorted()
.collect(collectors.tolist());
br.close();
system.out.println(words);
words.foreach(key-> system.out.println(key));
}
输出
*
*/
/**
//
2018/10/24
21:40
=
@author:
@date:
@description:
class
getname()
int
name)
参考
java 8 中的 streams api 详解
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对CodeAE代码之家的支持。
原文链接:http://www.cnblogs.com/kaituorensheng/p/9852462.html
http://www.zzvips.com/article/169722.html
页:
[1]