boolean isEmpty = StringUtils.isEmpty(str); 复制代码
boolean isEmpty = CollectionUtils.isNotEmpty(list); 复制代码
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); } 复制代码
2. stream
流操作相关的工具
List<User> userList = userService.getList(); //去掉某个字段为空的数据 userList = userList.stream().filter(s =>StringUtils.isEmpty(s.getPhone()).collect(Collectors.toList()); 复制代码
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()); 复制代码
//根据id进行排序 userList = userList.stream().sorted(User::getId()).collect(Collectors.toList()); //根据其它排序 userList = userList.stream().sorted((In1,In2) -> In1- In2).collect(Collectors.toList()); 复制代码
//判断是否有名字为jack的 boolean isExsit = userList.stream().anyMacth(s ->"jack".equals(s.getName())); //判断某个字段是否全为空 boolean isEmpty = userList.stream().nonoMatch(s -> s.getEmail().isEmpty()); 复制代码
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"); }) }); 复制代码
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()); 复制代码
一个新的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(); } } 复制代码
List<String> list = new ArrayList<String>(); list.add("1"); list.add("2"); list.add("3"); String result = Joiner.on("-").join(list); > 1-2-3 复制代码