背景
1.通常我们在获取到一个list列表后需要一个挨着一个的进行遍历处理数据,如果每次处理都需要长时间操作,那整个流程下来时间就是每一次处理时间的总和。
2.Java8的stream接口极大地减少了for循环写法的复杂性,stream提供了map/reduce/collect等一系列聚合接口,还支持并发操作:parallelStream。
例子
定义一个位置类和服务,其中创建10个地址位置
package cn.chinotan.dto;
/**
* @program: test
* @description: 位置
* @author: xingcheng
* @create: 2018-11-17 19:36
**/
public class Location {
String name;
public Location() {
}
public Location(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package cn.chinotan.controller;
import cn.chinotan.dto.Location;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
/**
* @program: test
* @description: 位置服务
* @author: xingcheng
* @create: 2018-11-17 19:42
**/
@RestController
public class LocationController {
@GetMapping("/location")
public List getLocations() {
List locations = new ArrayList<>();
for (int i = 0; i < 10; i++) {
locations.add(new Location(StringUtils.join("London", i)));
}
return locations;
}
}
定义一个温度类和服务,其中温度值介于30到50之间。 在实现中添加500 ms的延迟以模拟耗时操作
package cn.chinotan.dto;
/**
* @program: test
* @description: 温度
* @author: xingcheng
* @create: 2018-11-17 19:35
**/
public class Temperature {
private Double temperature;
private String scale;
public Double getTemperature() {
return temperature;
}
public void setTemperature(Double temperature) {
this.temperature = temperature;
}
public String getScale() {
return scale;
}
public void setScale(String scale) {
this.scale = scale;
}
}
package cn.chinotan.controller;
import cn.chinotan.dto.Temperature;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import java.util.Random;
/**
* @program: test
* @description: 温度服务
* @author: xingcheng
* @create: 2018-11-17 19:45
**/
@RestController
public class TemperatureController {
@GetMapping("/temperature/{city}")
public Temperature getAverageTemperature(@PathVariable("city") String city) {
Temperature temperature = new Temperature();
temperature.setTemperature((double) (new Random().nextInt(20) + 30));
temperature.setScale("Celsius");
try {
Thread.sleep(500);
} catch (InterruptedException ignored) {
}
return temperature;
}
}
定义一个天气预报类和响应
package cn.chinotan.dto;
/**
* @program: test
* @description: 天气预报
* @author: xingcheng
* @create: 2018-11-17 19:37
**/
public class Forecast implements Comparab