原创转载请注明出处:http://agilestyle.iteye.com/blog/2424918
Definition
A short definition is “a sequence of elements from a source that supports data processing operations.”
Sequence of elements — Like a collection, a stream provides an interface to a sequenced set of values of a specific element type. Because collections are data structures, they’re mostly about storing and accessing elements with specific time/space complexities (for example, an ArrayList vs. a LinkedList). But streams are about expressing computations such as filter, sorted, and map that you saw earlier. Collections are about data; streams are about computations.
Source — Streams consume from a data-providing source such as collections, arrays, or I/O resources.
Note that generating a stream from an ordered collection preserves the ordering. The elements of a stream coming from a list will have the same order as the list.
Data processing operations — Streams support database-like operations and common operations from functional programming languages to manipulate data, such as filter, map, reduce, find, match, sort, and so on. Stream operations can be executed either sequentially or in parallel.
Pipelining — Many stream operations return a stream themselves, allowing operations to be chained
and form a larger pipeline. This enables certain optimizations, such as laziness and short-circuiting. A pipeline of operations can be viewed as a database-like query on the data source.
Internal iteration — In contrast to collections, which are iterated explicitly using an iterator,
stream operations do the iteration behind the scenes for you.
Chaining stream operations forming a stream pipeline
e.g.
package org.fool.java8.stream; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; public class StreamTest1 { public static void main(String[] args) { List<Dish> menu = Arrays.asList( new Dish("pork", false, 800, Dish.Type.MEAT), new Dish("beef", false, 700, Dish.Type.MEAT), new Dish("chicken", false, 400, Dish.Type.MEAT), new Dish("french fries", true, 530, Dish.Type.OTHER), new Dish("rice", true, 350, Dish.Type.OTHER), new Dish("season fruit", true, 120, Dish.Type.OTHER), new Dish("pizza", true, 550, Dish.Type.OTHER), new Dish("prawns", false, 300, Dish.Type.FISH), new Dish("salmon", false, 450, Dish.Type.FISH) ); List<String> lowCaloricDishesName = menu.parallelStream() .filter(d -> d.getCalories() < 400) .sorted(Comparator.comparing(Dish::getCalories)) .map(Dish::getName) .collect(Collectors.toList()); System.out.println(lowCaloricDishesName); } public static class Dish { private String name; private boolean vegetarian; private int calories; private Type type; public Dish(String name, boolean vegetarian, int calories, Type type) { this.name = name; this.vegetarian = vegetarian; this.calories = calories; this.type = type; } public enum Type { MEAT, FISH, OTHER } public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean isVegetarian() { return vegetarian; } public void setVegetarian(boolean vegetarian) { this.vegetarian = vegetarian; } public int getCalories() { return calories; } public void setCalories(int calories) { this.calories = calories; } public Type getType() { return type; } public void setType(Type type) { this.type = type; } @Override public String toString() { return "Dish{" + "name='" + name + '\'' + ", vegetarian=" + vegetarian + ", calories=" + calories + ", type=" + type + '}'; } } }
Console Output
[season fruit, prawns, rice]
稍作改动,让程序sleep一段时间
... List<String> lowCaloricDishesName = menu.parallelStream() .filter(d -> { try { Thread.sleep(10000000); } catch (InterruptedException e) { e.printStackTrace(); } return d.getCalories() < 400; }) .sorted(Comparator.comparing(Dish::getCalories)) .map(Dish::getName) .collect(Collectors.toList()); System.out.println(lowCaloricDishesName); ...
运行程序,打开jconsole,观察一下线程
连接
可以看到底层使用的是ForkJoin实现
Filtering a menu using a stream to find out three high-calorie dish names
e.g.
List<String> lowCaloricDishesName = menu.parallelStream() .filter(d -> d.getCalories() > 300) .sorted(Comparator.comparing(Dish::getCalories)) .map(Dish::getName) .limit(3) .collect(Collectors.toList());
Console Output
[rice, chicken, salmon]
Intermediate operations
Intermediate operations such as filter or sorted return another stream as the return type. This allows the operations to be connected to form a query. What’s important is that intermediate operations don’t perform any processing until a terminal operation is invoked on the stream pipeline—they’re lazy. This is because intermediate operations can usually be merged and processed into a single pass by the terminal operation.
Terminal operations
Terminal operations produce a result from a stream pipeline. A result is any nonstream value such as a List, an Integer, or even void.
Reference
Manning.Java.8.in.Action.Lambdas.Streams.and.functional-style.programming
相关推荐
RabbitMQ Stream 教程 - "Hello World!
在本文中,我们将深入探讨基于WebFlux的“HelloWorld”示例,这是一个使用Java和Spring框架构建的响应式Web应用程序。WebFlux是Spring Framework 5中引入的一个新特性,它提供了非阻塞和反应式的Web编程模型,旨在...
kinesis-flink-hello-world AWS Kinesis和Apache Flink示例 动因制片人 aws kinesis put-record --stream-name < yourCreatedStreamNameHere> --data ' {"hello":"test"} ' --partition-key " KEY0 " 免责声明 如果...
总的来说,"helloworld 小测试"是一个很好的起点,帮助初学者理解网络编程和服务器开发的基本概念。通过构建和运行这个控制服务器,我们可以学习如何建立网络连接,交换数据,以及如何在服务器端处理这些交互。这些...
java8流源码你好,世界 Me test repository AO test No. 1! :) ...#我需要的一组技术:领域驱动设计?...boot(呃,不适用于我想控制所有的大型应用程序......)TestDrivenDevelopment ...Strust.........基础.........
本文将深入探讨"C++ Socket Hello World"这个话题,通过学习基础的Socket编程,你可以理解如何在C++环境下构建简单的TCP客户端(TCPClient)和服务器(TCPServer)。 首先,让我们了解什么是Socket。Socket是操作系统...
fs.writeFileSync('example.txt', "hello world");var stream = fs.createReadStream('example.txt');stream.pipe( replace('hello', 'goodbye') ).pipe(process.stdout);=> goodbye world使用缓冲区的
"Helloworld"是学习任何新框架时的经典入门示例,通过它我们可以了解Struts2的基本工作原理和配置。 首先,让我们深入了解Struts2的核心概念: 1. **Action类**:在Struts2中,业务逻辑通常被封装在Action类中。一...
这个“Struts2 视频之Struts2 HelloWorld”项目旨在引导初学者入门Struts2框架,通过实际操作理解其基本概念和工作原理。 在“Struts2-helloworld”压缩包中,我们通常会找到以下组件: 1. **源码**:源代码文件夹...
这个"Struts2_HelloWorld"例子是初学者踏入Struts2世界的绝佳起点,它通过一个简单的实例展示了如何在Struts2框架下创建并运行一个基本的Web应用。 首先,我们来看"HelloWorld"的实现过程。在Struts2中,我们通常会...
count ( from ( [ "hello" , "world" ] ) , function ( err , len ) { // len === 10 } ) 执照 麻省理工学院许可证 (MIT) 版权所有 (c) 2014 威廉卡萨林 特此授予任何人免费获得本软件副本和相关文档文件(“软件...
本教程将详细介绍如何通过ROS建立一个工作区,并在其中实现“Hello, World!”的打印功能,同时涵盖C++和Python两种编程语言的实现方式。 首先,我们需要创建一个ROS工作区。ROS工作区是存放源代码、编译结果和依赖...
流内容 在流和缓冲区(或字符串)之间转换。 用法 var sc = require ( 'stream-content' ) ;... writeAll ( writableStream , 'hello world' , function ( err ) { console . log ( 'done' ) ; }
res.end('Hello, Stream World!'); }); server.listen(3000, () => { console.log('Server is running on port 3000'); }); ``` 这个示例展示了一个基本的HTTP服务器,它接收请求并发送简单的响应。实际的`node-...
java8 ...Helloworld programs in different languages,pull requests are welcome :) Awk - A script that cleans up the php.ini file with security in mind Batchfile - Python best practices gui
本项目"ffmpeg_android_helloworld.zip"是知名开发者leixiaohua的一个作品,旨在为初学者提供一个在Android上集成和使用FFmpeg的入门示例。 项目"FFmpegAndroidHelloworld"主要包括以下几个关键知识点: 1. FFmpeg...
Kafka测试Hello World示例 此使用开放源代码库进行声明式样式测试。 可以克隆和运行多种口味的。 运行测试之前,请确保启动 。 让我们学习自动测试Kafka应用程序的最简单,最有效的方法。 在以下情况下特别有用: ...
Cocos2d-x的“HelloWorld”项目是每个新开发者入门的起点,它展示了如何创建一个简单的显示“Hello, World!”的窗口。 2. **Jsoncpp解析** Jsoncpp是一个轻量级的JSON库,它支持C++98、C++11和C++14标准。Jsoncpp...
1. **源代码文件**:可能有一个或多个`.java`文件,比如上述的`HelloWorld.java`,存放着"Hello, World"程序的源代码。 2. **编译后的字节码**:在Java中,源代码会被编译成`.class`文件,这些文件可以直接由JVM运行...
在这个“CXF整合spring 支持restful xml json 上传下载的HelloWorld”示例中,我们将探讨如何实现XML和JSON数据格式的支持,以及文件上传和下载功能。 首先,我们需要在Spring配置文件中声明CXF的Servlet,这样可以...