极悦小编来告诉大家基本的Stream用法。
List集合创建Stream
List<String> lists = new ArrayList();
Stream<String> stream = lists.stream();
Set集合创建Stream
Set<String> sets = new HashSet<();
Stream<String> stream1 = sets.stream();
Map集合创建Stream
Map<String,String> map = new HashMap<>();
Stream<String>stream2=map.keySet().stream();
Stream<String>stream3=map.values().stream();
Stream<Map.Entry<String,String>>stream4=map.entrySet().stream();
Stream.of方法创建Stream
Integer[] arr ={1,2,3,4,5,6};
Stream<Integer>arr1=Stream.of(arr);
Stream<String> stringStream = Stream.of("1","2","3", "4");
ForEach方法 (循环方法)
Stream.of(1,2,3,4,5,6).forEach(item ->{System.out.println(item);});
//优化后
Stream.of(1,2,3,4,5,6).forEach(System.out::println);
//打印 1,2,3,4,5,6
Filter方法(过滤方法)
Stream<Integer>arr1=Stream.of(1,2,3,4,5,6,7,8,9,10,1,5,6,8);
arr1.filter(item ->{return item > 5;}).forEach(item -> System.out.println(item));
//优化后
arr1.filter(item -> item > 5).forEach(System.out::println);
//打印 6,7,8,9,10,6,8
Map方法(转换or映射方法)
Stream<Integer>arr1=Stream.of(1,2,3,4,5,6,7,8,9,10,1,5,6,8);
arr1.map(item -> { return item + 5;}).forEach(item -> System.out.print(item+","))
//优化后
arr1.map(item -> item + 5).forEach(System.out::print);
//打印 6,7,8,9,10,11,12,13,14,15,6,10,11,13
Count(统计方法,统计当前流中的数据)
Stream<Integer> arr1 = Stream.of(1,2,3,4,5,6,7,8,9,10,1,5,6,8);
System.out.println(arr1.count());
//打印 14
limit(截取方法,截取指定长度内的数据)
Stream<Integer> arr1 = Stream.of(1,2,3,4,5,6,7,8,9,10,1,5,6,8);
arr1.limit(5).forEach(item -> System.out.print(item+","))
//优化后
arr1.limit(5).forEach(System.out::print);
//打印 1,2,3,4,5
skip(跳过元素,如果跳过数值大于当前长度则返回空)
Stream.of(1,2,3,4,5,6,7,8,9,10).skip(8).forEach(item -> System.out.println(item));
//优化后
Stream.of(1,2,3,4,5,6,7,8,9,10).skip(8).forEach(System.out::println));
//打印 9,10
concat(静态方法.将多个流组成一个流)
Stream<Integer> stream1 = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
Stream<String> stream2 = Stream.of("a", "b", "c", "d");
Stream.concat(stream1,stream2).forEach(item -> System.out.println(item));
//优化后
Stream.concat(stream1,stream2).forEach(System.out::println);
//打印 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,"a", "b", "c", "d"
延迟方法概念
返回值仍然是Stream本身的方法,可以链式调用(除了中介方法外,其他的方法均是延迟方法).
终结方法概念
返回值类型不再是Stream本身方法,不再支持链式编程.(count,forEach)
注意
Stream属于管道流,只能使用一次,使用完成以后会关闭管道,如果在调用就会报错(stream has already been operated upon or closed)
以上就是关于“基本的Stream用法”的介绍,大家如果对此比较感兴趣,想了解更多相关知识,不妨来关注一下极悦的Java8 Stream流的使用,相信对大家一定会有所帮助的。
你适合学Java吗?4大专业测评方法
代码逻辑 吸收能力 技术学习能力 综合素质
先测评确定适合在学习