StreamUtils.java
3.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package com.lhcredit.common.utils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class StreamUtils<T> {
public Stream<T> stream;
public List<T> list;
public static <T> StreamUtils<T> of(List<T> list){
StreamUtils streamUtils = new StreamUtils();
streamUtils.stream= CollectionUtils.isEmpty(list)?null:list.stream();
streamUtils.list=list;
return streamUtils;
}
//将json对象转换为java对象
public <R> StreamUtils<R> changeJavaBean(Class<R> clazz){
if (isEmpty())return new StreamUtils<>();
StreamUtils<R> streamUtils= new StreamUtils<R>();
streamUtils.list=JSONArray.parseArray(JSONArray.toJSONString(list),clazz);
return streamUtils;
}
//将json对象转换为json对象
public StreamUtils<JSONObject> changeJSONObject(){
if (isEmpty())return new StreamUtils<>();
StreamUtils<JSONObject> streamUtils= new StreamUtils<JSONObject>();
streamUtils.list=list.stream().map(item-> JSONObject.parseObject(JSONObject.toJSONString(item))).collect(Collectors.toList());
return streamUtils;
}
public StreamUtils<T> sorted(Comparator<? super T> comparator) {
if (isEmpty())return new StreamUtils<>();
List<T> collect =list.stream().sorted(comparator).collect(Collectors.toList());
if (CollectionUtils.isEmpty(collect))return new StreamUtils<>();
this.list=collect;
return this;
}
public boolean isEmpty(){
return CollectionUtils.isEmpty(list);
}
public StreamUtils<T> filter(Predicate<T> predicate){
if (isEmpty())return new StreamUtils<>();
List<T> collect = list.stream().filter(predicate).collect(Collectors.toList());
if (CollectionUtils.isEmpty(collect))return new StreamUtils<>();
this.list=collect;
return this;
}
public <R> StreamUtils<R> map(Function<T,R> function){
if (isEmpty())return new StreamUtils<>();
StreamUtils<R> streamUtils = new StreamUtils<>();
List<R> collect = list.stream().map(function).collect(Collectors.toList());
if (CollectionUtils.isEmpty(collect))return streamUtils;
streamUtils.list=collect;
return streamUtils;
}
//获取列表第一个数据
public <T> T getFirst(){
if (isEmpty())return null;
return (T) list.get(0);
}
//获取list数据
public List<T> getList(){
if (isEmpty())return new ArrayList<>();
return list;
}
//获取list数据 如果为空返回当前对象
public List<T> getList(List<T> object){
if (isEmpty())return object;
return list;
}
public Object getList(JSONArray object){
if (isEmpty())return object;
return list;
}
}