后端集合操作汇总
StringUtils.isNotEmpty(param) 字符串是否为空的判断
1、获得集合中某一列数据形成一个新的集合
List<String> setCode =resultList.stream().map(e -> e.getSetCode()).collect(Collectors.toList());
2、集合中对象类型转换
List<RealityTaskEx> exList = ModelConverterUtils.convert(taskList, RealityTaskEx.class);
public static <T> List<T> convert(Collection<?> sources, Class<T> targetClass) {
if (sources == null) {
return null;
}
List<T> targets = Lists.newArrayList();
if (!CollectionUtils.isEmpty(sources)) {
targets = sources.stream().map(x -> convert(x, targetClass)).collect(Collectors.toList());
}
return targets;
}
3、数组转成集合
List<String> list = Arrays.asList(person);//String[] person
// List<String> 转成List<Long>
List<Long> amList = list.stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
4、集合根据某个字段去重
personList.stream().distinct().collect(Collectors.toList());
5、筛选符合条件的数据集合
List<RealitySchedule> schedule =sheduleList.stream().filter(e -> e.getSetId().equals(Long.parseLong(realitySet[0]))).collect(Collectors.toList());
//将集合转换成String类型
nameSet +=String.join(",",pmNameList.stream().distinct().filter(Objects::nonNull).collect(Collectors.toList()));
6、集合中是否包含某个对象值
Boolean exist= taskTypeList.stream().filter(t->t.equals(ConstantEnum.TASK_TYPE_MORING.getCode())).findAny().isPresent();
Boolean exist= taskTypeList.stream().anyMatch(t->t.equals(ConstantEnum.TASK_TYPE_MORING.getCode()));
7、获取yml文件中的值
import org.springframework.beans.factory.annotation.Value;
@Value("${spring.application.name}")
private String applicationName;
8、得到集合中的多个值
List<String> outBoxList = boxes.stream().map(s ->s.getId()+","+s.getBranchId()).collect(Collectors.toList())
outBoxList.stream().forEach(u ->{
// 根据逗号分开多个参数
String[] boxBranch = u.split(",");
// 查询集合中是否存在某个对象
OutWarehouseDetail detail =outList.stream().filter(o ->o.getBoxId().equals(boxBranch[0])).findFirst().orElse(null);
})
9、集合切片
<!--list 切片-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.4</version>
</dependency>
import org.apache.commons.collections4.ListUtils;
// 根据需求,将款箱三列展示 List<List<BaseCashBoxInfoEx>> partition = ListUtils.partition(returnList,3); if(CollectionUtils.isNotEmpty(partition)){ List<BaseCashBoxInfoEx> first =new ArrayList<>(); List<BaseCashBoxInfoEx> second = new ArrayList<>(); List<BaseCashBoxInfoEx> third =new ArrayList<>(); partition.stream().forEach( p ->{ int count =p.size(); if(count == 1){ first.add(p.get(0)); }else if(count == 2){ first.add(p.get(0)); second.add(p.get(1)); }else{ first.add(p.get(0)); second.add(p.get(1)); third.add(p.get(2)); } }); ex.setFirstBox(first); ex.setSecondBox(second); ex.setThirdBox(third); }
10、取两个集合的交接
List<OutWarehouseDetail> sameList = outList.stream().filter(boxReal::contains).collect(Collectors.toList());