体验stream
- 不使用stream流
public static void main(String[] args) throws ExecutionException, InterruptedException {
List<String> list = new ArrayList<>();
list.add("张无忌");
list.add("周芷若");
list.add("赵敏");
list.add("张强");
list.add("张三丰");
List<String> collect = new ArrayList();
for(String s : list){
if(s.startsWith("张")){
collect.add(s);
}
}
List<String> collect1 = new ArrayList();
for(String s : collect){
if(s.length() == 3){
collect1.add(s);
}
}
for(String s : collect1) {
System.out.println(s);
}
}
- 使用stream流
public static void main(String[] args) throws ExecutionException, InterruptedException {
List<String> list = new ArrayList<>();
list.add("张无忌");
list.add("周芷若");
list.add("赵敏");
list.add("张强");
list.add("张三丰");
// 一行代码解决
list.stream().filter(name -> name.startsWith("张"))
.filter(name->name.length() == 3)
.forEach(System.out::println);
}
Stream流的作用
结合了Lambda表达式,简化集合、数组的操作
Stream流的使用步骤
- 先得到一条Stream流(流水线),并把数据放上去
- 利用Stream流中的API进行各种操作
- 中间方法(方法调完还可以调用其它方法):过滤、转换
- 终结方法(方法调完不可以调用其它方法):统计、打印
怎么得到一条Stream流
获取方法 | 方法名 | 说明 |
单列集合 | default Stream stream() | Collection中的默认方法 |
双列集合 | 无 | 无法直接使用stream流 |
数组 | public static stream(T[] array) | Arrays工具类中的静态方法 |
一堆零散数据 | public static Stream of(T ...values ) | Stream接口中的静态方法 |
单列集合
public static void main(String[] args){
List<String> list = new ArrayList<>();
Collections.addAll(list,"a","b","c","d","e");
// 获取到一条流水线,并将集合中的数据放到流水线上
Stream<String> stream = list.stream();
// 使用终结方法打印流水上的所有数据
stream.forEach(new Consumer<String>() {
@Override
public void accept(String s) {
System.out.println(s);
}
});
// 使用链式编程(需要注释上面代码,stream只能用一次)
stream.forEach(System.out::println);
}
双列集合
public static void main(String[] args){
Map<String,Integer> map = new HashMap<>();
map.put("aaa",111);
map.put("bbb",222);
map.put("ccc",333);
map.put("ddd",444);
// 先转成单列集合再使用stream流
// map.keySet().stream().forEach(System.out::println);
map.entrySet().stream().forEach(System.out::println);
}
数组
public static void main(String[] args){
String[] arr = {"aaa","bbb","ccc","ddd"};
// 使用Arrays工具类中的stream方法
Arrays.stream(arr).forEach(System.out::println);
}
零散数据
public static void main(String[] args){
Stream.of("a","b","c").forEach(System.out::println);
}
Stream流的中间方法
名称 | 说明 |
Stream filter(Predicate<? super T predicate>) | 过滤 |
Stream limit(long maxSize) | 获取前几个 |
Stream skip(long n) | 跳过前几个元素 |
Stream distinct() | 元素去重,依赖hashCode和equals方法 |
static concat(Stream a,Stream b) | 合并a和b两个流为一个流 |
Stream map(Function<T,R> mapper) | 转换流中的数据类型 |
**注意1:**中间方法,返回新的Stream流,原来的Stream流只能使用一次,建议使用链式编程
**注意2:**修改Stream流中的数据,不会影响原来集合或者数组中的数据
filter
public static void main(String[] args){
List<String> list = new ArrayList<>();
Collections.addAll(list,"张无忌","周芷若","赵敏","张强","张三丰","张翠山","张良","王二麻子","谢广坤");
// 过滤,把张开头的留下,其余数据不要
list.stream().filter(name->name.startsWith("张"))
.filter(name->name.length()==3)
.forEach(System.out::println);
}
limit
public static void main(String[] args){
List<String> list = new ArrayList<>();
Collections.addAll(list,"张无忌","周芷若","赵敏","张强","张三丰","张翠山","张良","王二麻子","谢广坤");
// 获取前3个元素
list.stream().limit(3).forEach(System.out::println);
}
skip
public static void main(String[] args){
List<String> list = new ArrayList<>();
Collections.addAll(list,"张无忌","周芷若","赵敏","张强","张三丰","张翠山","张良","王二麻子","谢广坤");
// 跳过前4个元素
list.stream().skip(4).forEach(System.out::println);
}
distinct
public static void main(String[] args){
List<String> list = new ArrayList<>();
Collections.addAll(list,"张无忌","张无忌","张无忌","张无忌","张无忌","周芷若","赵敏","张强","张三丰","张翠山","张良","王二麻子","谢广坤");
// 获取前几个元素
list.stream().distinct().forEach(System.out::println);
}
底层使用hashSet去重,所以要重写hashCode和equals方法
concat
public static void main(String[] args){
List<String> list = new ArrayList<>();
Collections.addAll(list,"张无忌","张无忌","张无忌","张无忌","张无忌","周芷若","赵敏","张强","张三丰","张翠山","张良","王二麻子","谢广坤");
List<Integer> list2 = new ArrayList<>();
Collections.addAll(list2,1,2);
Stream.concat(list.stream(),list2.stream()).forEach(System.out::println);
}
map
/**
* @author xc
*/
public class solution {
public static void main(String[] args){
List<String> list = new ArrayList<>();
Collections.addAll(list,"张无忌-15","周芷若-20","赵敏-11","张强-14","张三丰-13","张翠山-91","张良-41","王二麻子-44","谢广坤-22");
list.stream().map(p -> {
String[] split = p.split("-");
return new P(split[0], Integer.parseInt(split[1]));
}).collect(Collectors.toList()).forEach(System.out::println);
}
}
class P{
private String name;
private int age;
public P(){}
public P(String name, int age) {
= name;
this.age = age;
}
@Override
public String toString() {
return "P{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
Stream流的终结方法
名称 | 说明 |
void forEach(Consumer action) | 遍历 |
long count() | 统计 |
toArray() | 收集流中的数据,放到数组中 |
collect(Collector collector) | 收集流中的数据,放到集合中 |
forEach
public static void main(String[] args){
List<String> list = new ArrayList<>();
Collections.addAll(list,"张无忌","周芷若","赵敏","张强","张三丰","张翠山","张良","王二麻子","谢广坤");
list.stream().forEach(name->System.out.println(name+"ss") );
}
toArray
public static void main(String[] args){
List<String> list = new ArrayList<>();
Collections.addAll(list,"张无忌","周芷若","赵敏","张强","张三丰","张翠山","张良","王二麻子","谢广坤");
String[] strings = list.stream().toArray(String[]::new);
for (String s : strings) {
System.out.println(s);
}
}
collect
/**
* @author xc
*/
public class solution {
public static void main(String[] args){
List<String> list = new ArrayList<>();
Collections.addAll(list,"张无忌-15","周芷若-20","赵敏-11","张强-14","张三丰-13","张翠山-91","张良-41","王二麻子-44","谢广坤-22");
list.stream().map(p -> {
String[] split = p.split("-");
return new P(split[0], Integer.parseInt(split[1]));
}).collect(Collectors.toList()).forEach(System.out::println);
}
}
class P{
private String name;
private int age;
public P(){}
public P(String name, int age) {
= name;
this.age = age;
}
@Override
public String toString() {
return "P{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
收集方法
收集成集合
/**
* @author xc
*/
public class solution {
public static void main(String[] args){
List<String> list = new ArrayList<>();
Collections.addAll(list,"张无忌-15","周芷若-20","赵敏-11","张强-14","张三丰-13","张翠山-91","张良-41","王二麻子-44","谢广坤-22");
List<P> collect = list.stream().map(v->new P(v.split("-")[0],Integer.parseInt(v.split("-")[1]))).collect(Collectors.toList());
for (P s : collect) {
System.out.println(s);
}
}
}
class P{
private String name;
private int age;
public P(){}
public P(String name, int age) {
= name;
this.age = age;
}
@Override
public String toString() {
return "P{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
收集成set
/**
* @author xc
*/
public class solution {
public static void main(String[] args){
List<String> list = new ArrayList<>();
Collections.addAll(list,"张无忌-15","周芷若-20","赵敏-11","张强-14","张三丰-13","张翠山-91","张良-41","王二麻子-44","谢广坤-22");
Set<P> collect = list.stream().map(v->new P(v.split("-")[0],Integer.parseInt(v.split("-")[1]))).collect(Collectors.toSet());
for (P s : collect) {
System.out.println(s);
}
}
}
class P{
private String name;
private int age;
public P(){}
public P(String name, int age) {
= name;
this.age = age;
}
@Override
public String toString() {
return "P{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
收集成Map
public class solution {
public static void main(String[] args){
List<String> list = new ArrayList<>();
Collections.addAll(list,"张无忌-15","周芷若-20","赵敏-11","张强-14","张三丰-13","张翠山-91","张良-41","王二麻子-44","谢广坤-22");
Map<String,Integer> collect = list.stream().collect(Collectors.toMap(s->s.split("-")[0],v->Integer.parseInt(v.split("-")[1])));
for (Map.Entry<String, Integer> m : collect.entrySet()) {
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
注意:收集过程中key不能重复,否则会报错
练习
public class solution {
public static void main(String[] args){
List<Integer> list = new ArrayList<>();
Collections.addAll(list,1,2,3,4,5,6,7,8,9,10);
List<Integer> collect = list.stream().filter(n -> n % 2 == 0).collect(Collectors.toList());
for (Integer i : collect) {
System.out.println(i);
}
}
}
public class solution {
public static void main(String[] args){
List<String> list = new ArrayList<>();
Collections.addAll(list,"zhangsan,23","lisi,24","wangwu,25");
Map<String, Integer> collect = list.stream()
.filter(p -> Integer.parseInt(p.split(",")[1]) >= 24)
.collect(Collectors.toMap(k -> k.split(",")[0], v -> Integer.parseInt(v.split(",")[1])));
for (Map.Entry<String, Integer> m : collect.entrySet()) {
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* @author xc
*/
public class solution {
public static void main(String[] args){
List<String> list1 = new ArrayList<>();
Collections.addAll(list1,"张三,23","李四,24","王五,25","刘麻子,26","林俊杰,27","鲁智深,28");
List<String> list2 = new ArrayList<>();
Collections.addAll(list2,"张三1,23","杨四2,24","王五3,25","杨麻子4,26","黑狗5,27","赵云6,28");
Stream<String> stream1 = list1.stream().filter(s -> s.split(",")[0].length() == 3).limit(2);
Stream<String> stream2 = list2.stream().filter(s -> s.split(",")[0].startsWith("杨")).skip(1);
List<Actor> collect = Stream.concat(stream1, stream2).map(s -> new Actor(s.split(",")[0], Integer.parseInt(s.split(",")[1]))).collect(Collectors.toList());
for (Actor actor : collect) {
System.out.println(actor);
}
}
}
class Actor{
private String name;
private int age;
public Actor(){}
public Actor(String name, int age) {
= name;
this.age = age;
}
@Override
public String toString() {
return "P{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}