package com.zc.learn;
import java.sql.SQLOutput;
import java.util.*;
import java.util.function.Function;
import java.util.function.IntFunction;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* @author congcong
*/
public class Stream流 {
/**
* 创建流
*/
public static void createStream() {
// 1、单列集合
Stream<String> streamList = new ArrayList<String>().stream();
Stream<String> streamSet = new HashSet<String>().stream();
// 2、数组
Stream<String> streamArray = Arrays.stream(new String[10]);
// 3、散列数据
Stream<String> stringStream = Stream.of("a", "b");
}
/**
* stream流中间操作
* 注意:1、中间方法返回的是新的stream流,原来的stream流只能使用一次,建议使用链式编程
* 2、修改stream流中的数据不会影响原来集合或数组中的数据
*/
public static void middleAction() {
List<String> list = new ArrayList<>();
Collections.addAll(list, "张无极", "周芷若", "赵敏", "张三丰", "张翠山");
// 1、filter(Predicate<? super T> predicate) 过滤
List<String> list1 = list.stream().filter(name -> name.startsWith("张")).collect(Collectors.toList());
/**
* 张无极
* 张三丰
* 张翠山
*/
list1.forEach(name -> System.out.println(name));
/**
* 2、limit(long maxSize) 获取前几个元素
* 张无极
* 周芷若
* 赵敏
*/
list.stream().limit(3).forEach(name -> System.out.println(name));
/**
* 3、skip(long n) 跳过前几个元素
* 张三丰
* 张翠山
*/
list.stream().skip(3).forEach(name -> System.out.println(name));
/**
* 4、distinct() 元素去重,依赖hashCode和equals方法
*
*/
List<String> distincList = new ArrayList<>();
Collections.addAll(distincList, "张无极", "周芷若", "赵敏", "张三丰", "张翠山", "张无极");
distincList.stream().distinct().forEach(name -> System.out.println(name));
//5、static<T> Stream<T> concat(Stream a, Stream b) 合并两个流为一个流
Stream.concat(list.stream(), distincList.stream()).forEach(name -> System.out.println(name));
/**
* 6、map(Function<T, R> mapper) 转换流中的数据类型
* 26
* 25
* 27
*/
List<String> mapList = new ArrayList<>();
Collections.addAll(mapList, "张无极-26", "周芷若-25", "赵敏-27");
mapList.stream().map(name -> {
String age = name.split("-")[1];
return Integer.parseInt(age);
}).forEach(age -> System.out.println(age));
}
/**
* stream流终结操作
*/
public static void endAction() {
/**
* 1、forEach(Consumer action) 遍历
*/
List<String> list = new ArrayList<>();
Collections.addAll(list, "张无极", "周芷若", "赵敏", "张三丰", "张翠山");
list.stream().forEach(name -> System.out.println(name));
/**
* 2、count() 统计
*/
System.out.println(list.stream().count()); //5
/**
* 3、toArray() 收集流中数据放到数组
* 张无极
* 周芷若
* 赵敏
* 张三丰
* 张翠山
*/
String[] array = list.stream().toArray(value -> new String[value]);
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
/**
* 4、collect(Collector collector) 收集流中数据放到集合中
*/
List<String> collect = list.stream().filter(name -> name.startsWith("张")).collect(Collectors.toList());
List<String> mapList = new ArrayList<>();
Collections.addAll(mapList, "张无极-26", "周芷若-25", "赵敏-27");
Map<String, String> map = mapList.stream().collect(
Collectors.toMap(
(name -> name.split("-")[0]),
(name -> name.split("-")[1])
)
);
//{张无极=26, 周芷若=25, 赵敏=27}
System.out.println(map);
}
}
Stream流复习总结
最新推荐文章于 2024-06-14 15:02:13 发布