s-day07--获取Stream流的两种方式(重点)
This commit is contained in:
@@ -40,7 +40,7 @@ public class Demo08 {
|
||||
System.out.println("-------------");
|
||||
//------------------------Stream流对以上代码进行优化-------------------------------------
|
||||
list.stream()
|
||||
.filter(s->s.startsWith("张"))
|
||||
.filter(s->{return s.startsWith("张");})
|
||||
.filter(s->s.length() == 3)
|
||||
.forEach(s-> System.out.println(s));
|
||||
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.inmind.stream03;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.*;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/*
|
||||
22.获取Stream流的两种方式(重点)
|
||||
Stream流的获取方式:
|
||||
1.单列集合Collection的stream方法,得到单列集合的stream流
|
||||
Collection接口
|
||||
default Stream<E> stream() 返回一个序列 Stream与此集合作为其来源。
|
||||
2.Stream接口的of方法,将多个数据组成一个流
|
||||
Stream接口
|
||||
static <T> Stream<T> of(T... values) 返回其元素是指定值的顺序排序流。
|
||||
*/
|
||||
public class Demo09 {
|
||||
public static void main(String[] args) {
|
||||
//单列集合获取流的方式
|
||||
//1.list集合
|
||||
ArrayList<Integer> list = new ArrayList<>();
|
||||
Collections.addAll(list, 1, 2, 3, 4, 5, 5, 5, 5);
|
||||
Stream<Integer> stream = list.stream();
|
||||
System.out.println(stream);
|
||||
//2.set集合
|
||||
HashSet<Integer> sets = new HashSet<>();
|
||||
Collections.addAll(sets, 1, 2, 3, 4, 5, 5, 5);
|
||||
Stream<Integer> stream1 = sets.stream();
|
||||
System.out.println(stream1);
|
||||
//Map双列集合,没有定义stream方法的,只能通过转为单列集合间接获取流
|
||||
HashMap<Integer, String> map = new HashMap<>();
|
||||
map.put(1, "貂蝉");
|
||||
map.put(2, "孙尚香");
|
||||
Set<Integer> keySet = map.keySet();//将所有的键保存到set集合
|
||||
System.out.println(keySet.stream());
|
||||
Collection<String> values = map.values();//将所有的值保存到单列集合
|
||||
System.out.println(values.stream());
|
||||
Set<Map.Entry<Integer, String>> entries = map.entrySet();//将所有的键值对对象保存到set集合
|
||||
System.out.println(entries.stream());
|
||||
|
||||
//Stream接口的静态方法of得到流对象
|
||||
Stream<Integer> stream2 = Stream.of(1, 2, 3, 4, 5, 5, 5, 5);
|
||||
Stream<Double> doubleStream = Stream.of(1.1, 1.2, 1.3);
|
||||
// Stream<? extends Serializable> stream3 = Stream.of(1, 1.1, "java", true);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user