1.Stream流式思想
当使用一个流的时候,通常包括三个基本步骤:获取一个数据源(source)→ 数据转换→执行操作获取想要的结 果,每次转换原有 Stream 对象不改变,返回一个新的 Stream 对象(可以有多次转换),这就允许对其操作可以 像链条一样排列,变成一个管道。
2.获取Stream流
1).所有的 单列集合都可以通过 stream() 默认方法获取流;
1.用stream()方法获取【针对单列集合】
Stream<String> listStream = new ArrayList<String>().stream();
Stream<String> setStream = new HashSet<String>().stream();
2).Stream 接口的静态方法 of 可以获取数组对应的流。
2.用.Stream 接口的静态方法 of()获取【针对数组】
Stream<String> strStream = Stream.of("1,2,3");
Stream<Integer> intStream = Stream.of(1,2,3);
3.Stream流常用用方法
1).forEach【逐一处理】
**void forEach(Consumer<? super T> action);**
**例:**
class StreamDemo2 {
public static void main(String[] args) {
Stream<String> stream = Stream.of("张三","李四","王五","赵六");
stream.forEach(name-> System.out.println("name = " + name));
}
}
2).filter【过滤】
**Stream<T> filter(Predicate<? super T> predicate);**
**例:**
class StreamDemo3 {
public static void main(String[] args) {
Stream<String> stream1 = Stream.of("张三","李四","张翠山","张家口");
//过滤开头是张的元素
Stream<String> stream2 = stream1.filter(name -> name.startsWith("张"));
//遍历结果
stream2.forEach(name-> System.out.println("name = " + name));
}
}
3).map【映射】
<R> Stream<R> map(Function<? super T, ? extends R> mapper);
例:
class StreamDemo4 {
public static void main(String[] args) {
// 获取String类型的流
Stream<String> stream1 = Stream.of("1","2","3","4");
// 把字符串类型转换为整数类型
Stream<Integer> stream2 = stream1.map(str -> Integer.parseInt(str));
// 遍历
stream2.forEach(name-> System.out.println(name+1));
}
}
4).count【计数】等同于size
long count();
例:
class StreamDemo5 {
public static void main(String[] args) {
// 获取String类型的流
Stream<String> stream1 = Stream.of("1","2","3","4");
long count = stream1.count();
System.out.println(count);
}
}
5).limit【取用前几个】
Stream<T> limit(long maxSize);
例:
class StreamDemo6 {
public static void main(String[] args) {
// 获取String类型的流
Stream<String> stream1 = Stream.of("天", "地", "玄", "黄", "宇", "宙", "洪", "荒");
// 调用limit截取前4个
Stream<String> limit = stream1.limit(4);
// 遍历limit
limit.forEach(name-> System.out.println(name));
}
}
6).skip【跳过前几个】
Stream<T> limit(long maxSize);
例:
class StreamDemo7 {
public static void main(String[] args) {
// 获取String类型的流
Stream<String> stream1 = Stream.of("天", "地", "玄", "黄", "宇", "宙", "洪", "荒");
// 调用limit截取前4个
Stream<String> limit = stream1.skip(4);
// 遍历limit
limit.forEach(name-> System.out.println(name));
}
}
7).concat【组合】将两个集合合起来
Stream<T> limit(long maxSize);
例:
class StreamDemo8 {
public static void main(String[] args) {
// Stream流1
Stream<String> s1 = Stream.of("天", "地", "玄", "黄");
// Stream流2
Stream<String> s2 = Stream.of("宇", "宙", "洪", "荒");
// 合并
Stream<String> concat = Stream.concat(s1, s2);
// 遍历
concat.forEach(name-> System.out.println("name = " + name));
}
}
网友评论