1. 空值判断
1. 空字符串判断
boolean isEmpty = StringUtils.isEmpty(str);
复制代码
2. 空集合判断
boolean isEmpty = CollectionUtils.isNotEmpty(list);
复制代码
3. 对象判空,在某些其它的工具类中 StringUtils
既可以对字符串判空,也可以对对象进行判空
org.apache.commons.lang3
包
StringUtils.isEmpty(CharSequence cs);
public static boolean isEmpty(CharSequence cs){
return cs == null || cs.length() ==0
}
复制代码
- 在
org.springframework.util
参数类型是Object的
public static boolean isEmpty(Object obj){
return obj == null || "".equals(obj);
}
复制代码
4. 字符串转集合
// str = "2,5,8,7";
String str = "2,5,8,7";
List<Integer> idList = StringUtil.stringToList(str,",");
复制代码
2.stream
流操作相关的工具
1. 集合去重过滤
List<User> userList = userService.getList();
//去掉某个字段为空的数据
userList = userList.stream().filter(s =>StringUtils.isEmpty(s.getPhone()).collect(Collectors.toList());
复制代码
2. 遍历操作
userList = userList.stream().map(user -> user.getName());
userList = userList.stream().map(user -> user.getName()).forEach(str -> {System.out.println(str)})
//提取所有的id
List<Integer> ids = userList.stream().map(User::getId()).collect(Collectors.toList());
复制代码
3. 排序操作
//根据id进行排序
userList = userList.stream().sorted(User::getId()).collect(Collectors.toList());
//倒序 不加reversed 顺序
userList = list.stream()
.sorted(Comparator.comparing(User::getAge).reversed())
.collect(Collectors.toList());
//根据其它排序
userList = userList.stream().sorted((In1,In2) -> In1- In2).collect(Collectors.toList());
复制代码
4. 判断操作
//判断是否有名字为jack的
boolean isExsit = userList.stream().anyMacth(s ->"jack".equals(s.getName()));
//判断某个字段是否全为空
boolean isEmpty = userList.stream().nonoMatch(s -> s.getEmail().isEmpty());
复制代码
5. 对象集合分组去重
Map<Integer, List<PurchaseUpdate>> maps = updates.stream().collect(Collectors.groupingBy(PurchaseUpdate::getWriteId, Collectors.toList()));
maps.forEach((k,v) ->{
v.forEach(update ->{
vo.setId(update.getId());
vo.setNumber(update.getCount());
purchaseService.update(vo);
build.append("xxxxx---------xxxxxx");
})
});
复制代码
6. 对象集合抽取某个元素组成新的数据或者按照符号拼接
String currentIds = list.stream().map(p ->p.getCurrentUser() == null ? null : p.getCurrentUser().toString()).collect(Collectors.joining(","));
List<Integer> ids = list.stream().map(User::getId).collect(Collectors.toList());
复制代码
7. 集合某个字段求和
IntSummaryStatistics st = list.stream().mapToInt(Info::getAge).summaryStatistics();
System.out.println("求和:" + st.getSum());
System.out.println("平均数" + st.getAverage());
System.out.println("最大值:" + st.getMax());
System.out.println("总数:" +st.getCount());
复制代码
8. 集合转Map
Map<Integer,String> map = list.stream().collect(Collectors.toMap(Info::getAge ,Info::getName));
System.out.println(map.toString());
复制代码
9. list转set
Set<Info> collect = list.stream().collect(Collectors.toSet());
collect.forEach(e -> {
System.out.println(e.toString());
});
复制代码
10. list中对对个字段计算并求和
计算所有订单总共销售额
double total = details.stream()
.filter(e -> e.getPrice() != null && e.getAmountActual() != null)
.reduce(0.0 ,
( x, y)-> x + (y.getPrice().doubleValue() * y.getAmountActual().doubleValue()) ,Double::sum)
//如果本身字段是 BigDecimal类型
BigDecimal ss = details.stream().reduce(BigDecimal.ZERO, (x, y) ->
x.add(y.getAmountActual().multiply(y.getPrice())), BigDecimal::add);
复制代码
3.OkHttp3 请求, http请求
一个新的http客户端,使用简单,性能极好,可以完美代替HttpClient
//get 请求
OkHttpClient client = new OkHttpClient();
String run (String url) {
Request request = new Request.Builder()
.url(url)
.build();
try {
Response res = client.newCall(request).execute();
return res.body().string();
} catch (Exception e){
return e;
}
}
//Post请求
public static final MediaType JSON = MediaType.get("application/json;charset=utf-8");
String run (String url ,String json) {
RequestBody body = RequestBody.create(json,JSON);
Request request = new Request.Builder()
.url(url)
.body(body)
.build();
try {
Response res = client.newCall(request).execute();
return res.body().string();
}
}
复制代码
4. 集合转符号分割的字符串
List<String> list = new ArrayList<String>();
list.add("1");
list.add("2");
list.add("3");
String result = Joiner.on("-").join(list);
> 1-2-3
复制代码
代码示例
public List<WaterQualityDTO> getWaterQuality(String date, List<Integer> processIds) {
List<WaterQualityDTO> list = new ArrayList<>();
List<TaskOrderContent> taskList = contentRepository.findByTime(date,processIds);
//查询所有的化验指标数据
List<Indicators> indicators = indicatorsRepository.findAll();
Map<Long,Indicators> indicatMap = new HashMap<>();
if(!CollectionUtils.isEmpty(indicators)){
//list 转成Map 以id 和对象为 key和value indicatMap.putAll(indicators.stream().collect(Collectors.toMap(Indicators::getId, Function.identity())));
}
if(!CollectionUtils.isEmpty(taskList)){
//去重 合并
String ids = taskList.stream().map(TaskOrderContent::getProcessId)
.distinct()
.map(String::valueOf)
.collect(Collectors.joining(","));
Map<Integer, List<ProcessChainDTO>> processNames = processService.getProcessChainsByProcessIds(ids);
Map<Integer,List<TaskOrderContent>> group = taskList.stream().collect(
Collectors.groupingBy(TaskOrderContent ::getProcessId,Collectors.toList())
);
List<WaterQualityDTO.WaterRes> resList = new ArrayList<>();
group.forEach((k,v) ->{
resList.clear();
WaterQualityDTO waterAssay = new WaterQualityDTO();
String processName = processNames.get(k).stream().map(ProcessChainDTO::getName).collect(Collectors.joining("-"));
waterAssay.setPointName(processName);
waterAssay.setProcessId(k);
waterAssay.setTestDate(date);
v.stream().forEach(e ->{
WaterQualityDTO.WaterRes res = new WaterQualityDTO.WaterRes();
res.setCityName(processName);
res.setValue(e.getValue());
});
});
}
return null;
}
复制代码
近期评论