--Stream 8 new features of Java
A. Brief
Stream is a Java 8 presents a new collection of objects for enhanced functionality. It is a collection of Lambda
expression, the collection provides some very convenient and efficient operation, making the code has a very high readability, elegance! ! Take, for example, it's like a pipelining of things (fruit) input a series of pipeline processing, and finally we need to get some special fruits (unwashed apples).
- Stream provides a convenient way of handling the collection of
- Declarative programming ideas
- Code more elegant, simple, do not believe look down → _ →
For example to look at style Stream
Shanghai starting from July 1 this year, has been garbage unprecedented look at a diagram, below is Shanghai recently popular satchel (Behind his laugh cry), afraid, ha ha.
Much gossip that entered, now needs to be a pile of garbage
List<Garbage> garbages
classification.
- Use the Stream coding style
//有一堆没分类的垃圾
List<Garbage> garbage = new ArrayList<>();
//通过 Java 8 提供的流优雅的处理下,瞧好喽
List<Garbage> 干垃圾 = garbage.stream() //1. 垃圾倒出来,放到流水线
.filter(x -> "挑出有害垃圾") //2. 挑出有害垃圾
.filter(x -> "挑出可回收垃圾") //3. 挑出可回收垃圾
.filter(x -> "挑出有害垃圾") //4. 挑出有害垃圾
.collect(Collectors.toList()); //5. 把剩下的干垃圾装到干垃圾桶
/** 上面是不是非常优雅呢 **/
Two. Stream operation flow
Stream all operations are divided into three stages, [create] >> [intermediate] >> [operating] terminal operation
1. Stream of [create]
method one
list.stream()
//通过List集合创建 List<String> list = Arrays.asList("1", "2", "3"); //list.stream() Stream<String> stream = list.stream();
Second way
Stream.of()
//直接通过指定的元素创建 Stream<String> stream = Stream.of("1", "2", "3"); //通过数组Array String[] arrays = {"a", "b", "c"}; Stream<String> stream = Stream.of(arrays); //和上面区别不大 Stream<String> stream1 = Arrays.stream(arrays);
other
NUMERICAL operation of
the basic numeric, there are three types corresponding wrapper Stream:
IntStream.of(new int[]{1, 2, 3}).forEach(System.out::println);
IntStream.range(1, 3).forEach(System.out::println);
IntStream.rangeClosed(1, 3).forEach(System.out::println);
2. Stream pipelining intermediate operation] [
Common intermediate operation following formula
Stream Operation | Goal | Input |
---|---|---|
filter | A method for filtering a filter condition set by the element. | Conditions (returns a Boolean value) Predicate |
map | A method for mapping a result of each map element corresponding to | It may be a function Function |
limit | A method for obtaining limit specified number of streams | int value |
sorted | A method for sorting sorted convection | Comparator |
distinct | remove duplicates | -- |
parallel | Instead of the parallel flow method is parallelStream handler | -- |
- filter count the number of empty string
List<String>strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
// 获取空字符串的数量
int count = strings.stream().filter(string -> string.isEmpty()).count()
- map 使用 map 输出了元素对应的平方数
List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
// 获取对应的平方数
List<Integer> squaresList = numbers.stream().map( i -> i*i).distinct().collect(Collectors.toList());
- limit使用 limit 方法打印出 10 条数据
Random random = new Random();
random.ints().limit(10).forEach(System.out::println);
- sorted使用 sorted 方法对输出的 10 个随机数进行排序
Random random = new Random();
random.ints().limit(10).sorted().forEach(System.out::println);
- distinct使用 distinct 对元素进行去重
List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
numbers.stream().distinct().forEach(System.out::println);
- parallel 使用 parallelStream 来输出空字符串的数量
List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
// 获取空字符串的数量
int count = strings.parallelStream().filter(string -> string.isEmpty()).count();
3. 【终端操作】
Stream Operation | Goal | Input Or Output |
---|---|---|
forEach | 遍历元素 | 其他操作 |
count | 统计元素个数 | -- |
collect | 聚合操作 | -- |
- forEach遍历打印
Stream.of("a", "b", "c").forEach(System.out::println);
- count统计'a'的数量
long count = Stream.of("a", "b", "c", "a").filter(x -> "a".equals(x)).count();//2
- collect聚合
// 1. 聚合转成List
List<String> list1 = stream.collect(Collectors.toList());
List<String> list2 = stream.collect(Collectors.toCollection(ArrayList::new));
// 2. 聚合转成Set
Set set1 = stream.collect(Collectors.toSet());
Stack stack1 = stream.collect(Collectors.toCollection(Stack::new));
// 3. 聚合转成String
String str = stream.collect(Collectors.joining()).toString();
// 4. ···其他
三. 简单说下声明式编程
小故事:早上刚上班,经理找到大胖说:“大胖啊,咱们下去去聚餐,软件园旁边有好几家不错的餐馆,如巫山烤鱼、海底捞、大鸭梨,你到大众点评调查一下,也问问去过的同事,看看哪家的口碑好。我们有14个人,预定一张大桌子,然后用滴滴约4辆车,每辆车坐3~4人,我们会在11点半出发”。
如果经理是程序员,大胖是计算机,这就是典型的命令式编程
。
实际上,现实中一般是经理对大胖说:“大胖啊,我给你交代一件事,咱们下午要聚餐,你在软件园旁边找一家合适的餐馆,我们有14个人,11点半出发”。这种就是声明式编程
1. 声明式编程最知名的就是我们都熟悉的SQL
SELECT stu.id, stu.name, ss.score
FROM student stu, student_score ss
WHERE stu.id = ss.id
AND ss.score > 80
2. 用Java也来举个例子
有一个学生列表,计算出年龄小于18岁的学生数量
Traditional imperative programming
//声明一个计数器,遍历学生集合,如果学生年龄小于18岁,计数器+1
int count = 0;
Iterator<Student> iter = students.iterator();
while(iter.hasNext()) {
Student s = iter.next();
if (s.getAge < 18) {
count++;
}
}
Declarative Programming
//过滤学生构成的流(Stream),只把年龄小于18岁的留下,然后做个统计。
int count = students.stream()
.filter(s -> s.getAge() < 18)
.count();
Declarative programming is also a high degree of abstraction, I can only tell you that I want to do, as to how to do it, I Do not care