一、组成及特点
- 数据源、中间操作、终端操作
- 流只能使用一次
- 并行流 和 串行流
二、可以产生流的数据源 - 集合、文件
三、中间操作 - 字符串操作拼接joining(""),底层实现是StringBuilder.append();
//例1
private static String appendStr(){
List<String> stringList = Arrays.asList("h","e","l","l","o");
String str = stringList.stream().collect(Collectors.joining("-"));
//结果: h-e-l-l-o
return str;
}
//例2
public class ShangPin {
private String id;
private String mc;
//getter ..,setter
public static void main(String[] args) {
List<ShangPin> list = new ArrayList<>();
for (int i = 0; i < 5 ; i++) {
ShangPin shangPin = new ShangPin();
shangPin.setId(i+"");
shangPin.setMc("名称"+i);
list.add(shangPin);
}
//名称逗号分割
String mcs = list.stream().map( shangPin -> shangPin.getMc()).collect(Collectors.joining(","));
System.out.println(mcs);
}
}
- for循环
public static void test17(){
List<String> list = Arrays.asList("j","a","k","l");
list.forEach(x->{
System.out.println(x);
});
}
- 筛选
@Test
public void test7(){
List<String> stringList = new ArrayList<>();
JSONArray jsonArray = new JSONArray();
//数据源
for (int i = 0; i < 4; i++) {
stringList.add(i+"");
JSONObject jsonObject = new JSONObject();
jsonObject.put("num",i+"");
jsonArray.add(jsonObject);
}
//中间-筛选
Stream<String> stream = stringList.stream().filter(x -> "1".equals(x) || "3".equals(x));
Stream<JSONObject> _stream = jsonArray.stream().filter( o ->{
String num = ((JSONObject)o).getString("num");
return "1".equals(num) || "3".equals(num);
} );
//终端-收集 单个(类似 for循环里break )/集合
//String str = stream.findFirst().get();
//JSONObject json = _stream.findFirst().get();
List<String> str = stream.collect(Collectors.toList());
JSONArray _str = _stream.collect(Collectors.toCollection(JSONArray::new));
}
- for循环+break 被替换
- filter过滤,for循环里的 break 可以用 findFirst
public static void test11(){
String[] str = {"1","2","3","4","5","6","7","8","12","10","11","14"};
List<String> list = Arrays.asList(str);
String s = list.stream().filter( x -> (Integer.parseInt(x))%2 == 0).findAny().get();
System.out.println(s);
/*for (int i = 0; i < str.length; i++) {
if((Integer.parseInt(str[i]))%2 == 0){
System.out.println(str[i]);
break;
}
}*/
}
- 数值比较/求和/排序
public static void test12(){
String[] str = {"1","1","15","4","5","6","7","8","12","10","11","14"};
//转为int后求和
int sum = Arrays.stream(str).mapToInt(x -> Integer.parseInt(x)).sum();
//求和2,自定义
int sum2 = Arrays.stream(str).mapToInt(x -> Integer.parseInt(x)).reduce(2,(m,n)->m+n);
System.out.println(sum+"+2="+sum2);
//最大值max(),最小值min 比较器实现
String max = Arrays.stream(str).max(DemoApplicationTests::compator).get();
//数组长度
long length = Arrays.stream(str).count();
//排序 当前从小到大
List list = Arrays.stream(str).sorted(DemoApplicationTests::compator).collect(Collectors.toList());
System.out.println(list);
System.out.println(length);
System.out.println(sum+"--"+max);
}
private static int compator(String x1, String x2) {
if(Integer.parseInt(x1) < Integer.parseInt(x2)){
return -1;
}else if(Integer.parseInt(x1) == Integer.parseInt(x2)){
return 0;
}else{
return 1;
}
}
- 去重/截取
public static void test13(){
String[] str = {"1","1","15","4","11","6","7","8","12","10","11","14"};
//去重 distinct
List strList = Arrays.stream(str).distinct().collect(Collectors.toList());
//根据id去重
List<User> issueList = list.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<User>(
Comparator.comparing(User::getId))), ArrayList::new));
//前四(长度)个
List strList1 = Arrays.stream(str).limit(4).collect(Collectors.toList());
//跳过4个
List strList2 = Arrays.stream(str).skip(4).collect(Collectors.toList());
System.out.println(strList2);
}
public static void main(String[] args) {
List<User> users = new ArrayList<>();
users.add(new User(2, "Bob", "2021-01-02 09:00:00"));
users.add(new User(1, "Alice2", "2021-01-03 12:00:00"));
users.add(new User(1, "Alice", "2021-01-01 10:00:00"));
users.add(new User(3, "Charlie", "2021-01-04 08:00:00"));
users.add(new User(2, "Bob2", "2021-01-05 07:00:00"));
users.add(new User(4, "David", "2021-01-06 06:00:00"));
List<User> distinctUsers = users.stream()
.collect(Collectors.toMap(
User::getId,
user -> user,
(existingUser, newUser) -> {
if (newUser.getCreateTime().compareTo(existingUser.getCreateTime()) > 0) {
return newUser;
} else {
return existingUser;
}
}))
.values()
.stream()
.collect(Collectors.toList());
System.out.println(distinctUsers);
System.out.println("2021-01-01".compareTo("2021-01-02"));
}
}
- limit+skip 实现截取集合
- 分割集合
public static void test14(){
int dayNum = 5;
List<String> strList = Arrays.asList("2","2","2","2","2",
"4","4","4","4","4",
"8","8","8","8","8");
//总天数
int sumDay = strList.size();
//分3周
int week = sumDay%dayNum == 0 ? sumDay/dayNum:sumDay/dayNum+1;
List list = Stream.iterate(0,n->n+1).
//3周
limit(week).
//并行流
parallel().
map(
//循环,并返回值
num -> {
System.out.println(num);
List<String> list1 = strList.stream().
//跳过0*5个,取5个,即 0-5,
//跳过1*5;取5个,5-10,。。。
skip(num * dayNum).
limit(dayNum).
collect(Collectors.toList());
//求和
Double d = list1.stream().mapToDouble(x -> Double.valueOf(x) ).sum();
return d+"";
}
).
collect(ArrayList::new,ArrayList::add,List::addAll);
System.out.println(list);
}
- 数据处理 map,结果收集
public static void test15(){
//构建数据源
JSONArray jsonArray = new JSONArray();
for (int i = 0; i < 6 ; i++) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("mc","mc"+i);
jsonObject.put("xm","word"+i);
jsonArray.add(jsonObject);
}
//创建流
Stream<JSONObject> stream = jsonArray.stream();
//中间操作filter(条件过滤)/map(数据处理返回)/peek(调试时无返回)
Stream<JSONObject> streams = stream.
filter(obj -> !"mc0".equals(obj.getString("mc"))).
map(ele -> {
ele.put("xm","fyhh");
return ele;
});
//终端操作 收集/循环
JSONArray newArr = streams.collect(Collectors.toCollection(JSONArray::new));
//JSONArray newArr = streams.collect(JSONArray::new,JSONArray::add,JSONArray::addAll);
//JSONArray newArr = streams.collect(()-> new JSONArray(),(arrt,json)->{arrt.add(json);},(parr,json) ->{parr.addAll(json);});
//List list = streams.collect(Collectors.toCollection(ArrayList::new));
System.out.println(newArr);
}
- 逻辑与/或
public static void test16(){
List lsi = Arrays.asList("false","true","true");
//逻辑或,只要有一个为"true",即返回true,否则else; false||true||false 结果:false、true、--true(短路)
boolean flg = lsi.stream().anyMatch(x -> {
System.out.print(x+"、");
return "true".equals(x);
});
System.out.println("flg--"+flg);
//逻辑与 false&&true&&false 都为"true",才返回true,否则返回false
boolean flg2 = lsi.stream().allMatch(x -> {
System.out.print(x+"、");
return "true".equals(x);
});
System.out.println("flg2--"+flg2);
//anyMatch 取反,都不是"true",才返回true;否则else,
boolean flg3 = lsi.stream().noneMatch(x -> {
System.out.print(x+"、");
return "true".equals(x);
});
System.out.println("flg3--"+flg3);
}
四、数据收集collect
- List 转 Map
public static void test18(){
List<String> list = Arrays.asList("j","a","k","a","l");
//推荐
Map<String,String> mp = list.stream().collect(HashMap::new,(theMap,ele) -> {
theMap.put(ele,ele+"==");
},Map::putAll);
//不推荐,key重复会有异常 java.lang.IllegalStateException: Duplicate key a==
/* Map<String,String> collect2 = list.stream()
.collect(Collectors.toMap(ele ->ele,
ele ->ele+"=="));*/
System.out.println(mp);
}
- List 转JSONarray
public static void test20(){
List<JSONObject> list = new ArrayList<>();
for (int i = 0; i <4; i++) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("a"+i,22.5*i);
list.add(jsonObject);
}
JSONArray jsonArray = list.stream().collect(JSONArray::new,(theArr,json) -> {
theArr.add(json);
},JSONArray::addAll);
System.out.println(jsonArray);
}
- List<List<?>> 数据展平 stream().flatMap()
public void test(){
List<List<Integer>> arrList = new ArrayList<>();
for (int i = 1; i <= 2; i++) {
List<Integer> list = new ArrayList<>();
for (int j = 1; j <= 10; j++) {
list.add(Integer.valueOf(i*j));
}
arrList.add(list);
}
List<Integer> list = arrList.stream().flatMap(List::stream).collect(Collectors.toList());
System.out.println(list);
}
- 数据分组 Collectors.groupingBy()
public void testGroup(){
List<OderEntity> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
OderEntity order = new OderEntity();
order.setOrderId(i+"");
order.setRealId(i+"real");
if(i%3 == 0){
order.setAppName("alibaba");
} else if (i % 3 == 1) {
order.setAppName("JD");
} else if (i %3 == 2) {
order.setAppName("PDD");
}
list.add(order);
}
Map<String, List<OderEntity>> listMap = list.stream().collect(Collectors.groupingBy(x -> x.getAppName()));
listMap.get("JD").forEach(x-> {
System.out.println(x.getOrderId());
});
}
五、文件
public class FileUtils {
public static void main(String[] args) throws IOException, URISyntaxException {
FileUtils fileUtils = new FileUtils();
JSONObject json = fileUtils.getJsonFromCfg("/config/fyjing.json");
System.out.println(json);
}
/**
* json配置文职转为json
*/
public JSONObject getJsonFromCfg(String path) throws URISyntaxException, IOException {
//获取项目的绝对路径
URL allPath = FileUtils.class.getResource(path);
//URI 格式为 f:/F:/......
URI uri = allPath.toURI();
//Paths.get(uri) 为 F:/.....
String jsonStr = Files.lines(Paths.get(uri)).map(x->x.trim()).collect(Collectors.joining());
//字符串转json
JSONObject json = JSONObject.fromObject(jsonStr);
return json;
}
}
六、判断空指针
@Test
public void testw(){
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", "2");
String name = getNameJson(jsonObject);
}
private String getNameJson(JSONObject jsonObject) {
return Optional.ofNullable(jsonObject).map(x -> {
String name = x.getString("name");
return name;
}).orElseThrow(()->new RessException("",500));
}
7.Predicate
@Test
public void testP(){
Predicate<SuperUser> predicate = p -> "超人".equals(p.getName()) && "167777".equals(p.getPhone());
SuperUser user = new SuperUser();
user.setName("超人");
user.setPhone("167777");
if(predicate.test(user)){
System.out.println("这是超人!");
}
}
8.并行流
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
public class CompletableFutureDemo {
public static void main(String[] args) {
CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
// 这里是耗时操作
return 2;
});
CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> {
// 这里是耗时操作
return 3;
});
CompletableFuture<Integer> future3 = future1.thenCombineAsync(future2, (result1, result2) -> {
// 这里是将 future1 和 future2 的结果合并的操作
return result1 * result2;
});
try {
int result = future3.get();
System.out.println("Result: " + result);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
}
--本文作者:【ngLee 】
--关于博文:如果有错误的地方,还请留言指正。如转载请注明出处!如果您觉得文章对您有帮助,可以点击文章右下角【推荐】一下。您的鼓励是博主的最大动力!