一、Steam流的创建
Stream<Object> listStream = new ArrayList<>().stream(); //单列集合
Stream<Object> mapStream = new HashMap<>().keySet().stream();//双列集合
Stream<Object> arrayStream = Arrays.stream(new String[1]);//数组
Stream<Object> stream = Stream.of("a", "b");//零散数据
二、Stream流的中间方法
1.filter 过滤
List<String> list = new ArrayList<>();
Collections.addAll(list, "a", "a", "b", "c");
list.stream().filter(item -> item.equals("a")).forEach(System.out::println);// a a
结果:a a
2.limit 获取前几个元素
List<String> list = new ArrayList<>();
Collections.addAll(list, "a", "a", "b", "c");
list.stream().limit(3).forEach(System.out::println);//a a b
结果:a a b
3.skip 跳过前几个元素
List<String> list = new ArrayList<>();
Collections.addAll(list, "a", "a", "b", "c");
list.stream().skip(3).forEach(System.out::println);//c
结果:c
4.distinct 元素去重
List<String> list = new ArrayList<>();
Collections.addAll(list, "a", "a", "b", "c");
list.stream().distinct().forEach(System.out::println);//a b c
结果:a b c
5.concat 将两个流合并
List<String> list1 = new ArrayList<>();
Collections.addAll(list1, "a", "b", "c");
List<String> list2 = new ArrayList<>();
Collections.addAll(list2,"d", "e", "f");
Stream.concat(list1.stream(), list2.stream()).forEach(System.out::println);//a b c d e f
结果:a b c d e f
6.map 转换数据类型返回新集合等操作
List<String> list = new ArrayList<>();
Collections.addAll(list, "a-1", "b-2", "c-3");
list.stream().map(item -> item.split("-")[1]).forEach(System.out::println);//1 2 3
结果:1 2 3
三、Stream流的终结方法
1、forEach遍历
2、count计算个数
3、toArray收集成数组
List<String> list = new ArrayList<>();
Collections.addAll(list, "a", "b", "c");
//forEach
list.stream().forEach(System.out::println); //a b c
//count
long count = list.stream().count();
System.out.println(count); //3
//toArray
String[] strings = list.stream().toArray(item -> new String[item]);
System.out.println(Arrays.toString(strings));//[a, b, c]
结果:a b c
3
[a, b, c]
4、collect收集成集合(List Set Map)
List<String> list = new ArrayList<>();
Collections.addAll(list, "a", "b", "c");
//List
List<String> streamList = list.stream().collect(Collectors.toList());
System.out.println(streamList);//[a, b, c]
//Set
Set<String> streamSet = list.stream().collect(Collectors.toSet());
System.out.println(streamSet);//[a, b, c]
//Map
Map<Integer, String> streamMap = list.stream().collect(Collectors.toMap(item -> item.hashCode(), item -> item));
System.out.println(streamMap);//{97=a, 98=b, 99=c}
结果:[a, b, c]
[a, b, c]
{97=a, 98=b, 99=c}