forEach遍历Stream流对象
//获取一个stream流
Stream<String> stream = Stream.of("张三","李四","王五","赵六");
//使用stream流中的forEach遍历Stream流的对象
stream.forEach(name->System.out.println(name));
filter过滤流对象
Stream<String> stream = Stream.of("张三","张丽","飞洒发","多少分","很简单");
//使用filter过滤
Stream stream2 = stream.filter((name)->{return name.startsWith("张");});//过滤了所有以张为开头的姓名
stream2.forEach(name->System.out.println(name));
map映射(转换)
Stream<String> stream = Stream.of("1","2","3","4");
//将String类型的流转换为Integer类型
Stream<Integer> stream2 = stream.map((String num)->{return Integer.parseInt(num);});
stream2.forEach(num->System.out.println(num));
count计数(流中的个数)
Stream<String> stream = Stream.of("张三","张丽","飞洒发","多少分","很简单");
long count = stream.count();//返回值为long类型
System.out.println(count);//5
limit(int n)截取流中的数据,只取前n个数据
//获取一个Stream流
String[] arr = {"喜羊羊","美羊羊","沸羊羊","懒洋洋","灰太狼"};
Stream<String> stream1 = Stream.of(arr);
Stream<String> stream2 = stream1.limit(3);//只取前三个数据
stream2.forEach(name->System.out.println(name));
skip(int n)跳过前n个数据
//获取一个Stream流
String[] arr = {"喜羊羊","美羊羊","沸羊羊","懒洋洋","灰太狼"};
Stream<String> stream1 = Stream.of(arr);
Stream<String> stream2 = stream1.skip(2);//跳过前两个元素
stream2.forEach(name->System.out.println(name));
Stream.concat(a,b),将流a和流b连接成一个流
String[] arr = {"喜羊羊","美羊羊","沸羊羊","懒洋洋","灰太狼"};
Stream<String> stream1 = Stream.of(arr);
Stream<String> stream2 = Stream.of("张三","张丽","飞洒发","多少分","很简单");
//使用Stream中的concat方法将两个流合并成一个流
Stream<String> newStream = Stream.concat(stream1, stream2);
newStream.forEach(s->System.out.println(s));
练习
1.第一个队伍只要名字为3个字的成员姓名;存储到一个新集合中
2.第一个队伍筛选之后只要前3个人;存储到一个新集合中
3.第二个队伍只要姓张的成员姓名;存储到一-个新集合中。
4.第二个队伍筛选之后不要前2个人;存储到一-个新集合中。
5.将两个队伍合并为一一个队伍;存储到一-个新集合中。
6.根据姓名创建Person对象;存储到一-个新集合中。
7.打印整个队伍的Person对象信息
这个题如果使用集合去做会很麻烦,而使用流则很容易,这里就只展示流的做法了。首先要先定义一个Person类
Person类
package Demo01_StreamMethod;
public class Person {
private String name;
@Override
public String toString() {
return "Person [name=" + name + "]";
}
public Person(String name) {
super();
this.name = name;
}
public Person(){}
}
实现方法
package Demo01_StreamMethod;
import java.util.ArrayList;
import java.util.stream.Stream;
/*
1.第一个队伍只要名字为3个字的成员姓名;存储到一个新集合中
2.第一个队伍筛选之后只要前3个人;存储到一个新集合中
3.第二个队伍只要姓张的成员姓名;存储到一-个新集合中。
4.第二个队伍筛选之后不要前2个人;存储到一-个新集合中。
5.将两个队伍合并为一一个队伍;存储到一-个新集合中。
6.根据姓名创建Person对象;存储到一-个新集合中。
7.打印整个队伍的Person对象信息
*/
public class Demo08_test01 {
public static void main(String[] args) {
//队伍1
Stream<String> team1 = Stream.of("张三","小流","小玩意","王德峰","基金","小鱼干","刘德华","华夫妇","无妨")
.filter((String name)->{return name.length()==3;})
.limit(3);
//队伍2
Stream<String> team2 = Stream.of("张三","张丽","飞洒发","多少分","很简单","张雪","张伟")
.filter((String name)->{return name.startsWith("张");})
.skip(2);
//优化
Stream.concat(team1, team2).map((String name)->{return new Person(name);})
.forEach(person->System.out.println(person));
}
}