项目实战--Stream流实现字符拼接

需求:前端页面查询列表中有个多选的二级类目多选框,用户选择二级类目后,从后台数据库查询选择条件内的数据。

 项目实战--Stream流实现字符拼接

xxVo.java

 1 /**
 2  * 添加二级类目字段以及Getter和Setter方法
 3  */
 4 private String secondCateNames;
 5 
 6 public String getSecondCateNames() {
 7    return secondCateNames;
 8 }
 9 
10 public void setSecondCateNames(String secondCateNames) {
11    this.secondCateNames = secondCateNames;
12 }

Mapper.java

 1//二级类目查询
 2  //方法一
 3  if (StringUtils.isNoneBlank(vo.getSecondCateNames())) {
 4      String[] strArr = vo.getSecondCateNames().split(",");
 5      StringBuilder strBuilder = new StringBuilder();
 6      for (int i = 0; i < strArr.length; i++) {
 7          strBuilder.append("'").append(strArr[i]).append("'").append(",");
 8      }
 9      sql.append(" AND eod.second_cate_name in (" 
10              + strBuilder.substring(0, strBuilder.length()-1 ) + ")");
11  }
12  //方法二 运用Java8中的Stream表达式(推荐),告别For循环
13  if (StringUtils.isNotBlank(vo.getSecondCateNames())) {
14     //拼接前后单引号
15     String[] split = vo.getSecondCateNames().split(",");
16     List<String> secondCateNameList = Arrays.asList(split).stream().filter(Objects::nonNull)
17        .map(secondCateName -> "'" + secondCateName + "'").collect(Collectors.toList());
18     sql.append(" AND eod.second_cate_name in (")
19        .append(StringUtils.join(secondCateNameList, ",")).append(")");
20  }
  
  其中最后使用的StringUtils.join(final Iterable<?> iterable, final String separator)
等价于使用joining(CharSequence delimiter, CharSequence prefix, CharSequence suffix),该方法接受一个字符串序列作为拼接符,并在拼接完成后添加传递的前缀和后缀
//方法一
sql.append(" AND eod.second_cate_name in (").append(StringUtils.join(secondCateNameList, ",")).append(")");
//方法二
sql.append(" AND eod.second_cate_name in ").append(secondCateNameList.stream().collect(Collectors.joining(",","(",")")));

 

 

 

上一篇:leveldb - sstable格式


下一篇:H5,PC网页屏幕尺寸相关整理(scrollLeft,scrollWidth,clientWidth,offsetWidth)