导入失败数据导出接口

hehai
shijie 4 years ago
parent 4c8c065dd4
commit 5cd4262f23
  1. 7
      pom.xml
  2. 7
      src/main/java/com/msdw/tms/api/QuestionsControllerApi.java
  3. 5
      src/main/java/com/msdw/tms/common/utils/Constant.java
  4. 2
      src/main/java/com/msdw/tms/common/utils/poi/ExcelImportUtil.java
  5. 3
      src/main/java/com/msdw/tms/controller/PersonalFileController.java
  6. 3
      src/main/java/com/msdw/tms/controller/ProjectController.java
  7. 11
      src/main/java/com/msdw/tms/controller/QuestionsController.java
  8. 13
      src/main/java/com/msdw/tms/entity/request/QuestionsImportRequest.java
  9. 1
      src/main/java/com/msdw/tms/entity/response/CommonCode.java
  10. 76
      src/main/java/com/msdw/tms/entity/vo/QuestionsImportFailureVO.java
  11. 7
      src/main/java/com/msdw/tms/service/QuestionsService.java
  12. 2
      src/main/java/com/msdw/tms/service/impl/ProjectRecordServiceImpl.java
  13. 122
      src/main/java/com/msdw/tms/service/impl/QuestionsServiceImpl.java
  14. BIN
      src/main/resources/excel-template/试题导入失败数据导出模板.xlsx
  15. BIN
      src/main/resources/excel-template/试题导出模板.xlsx
  16. 181
      src/test/java/com/msdw/tms/TmsApplicationTests.java
  17. 26
      src/test/java/com/msdw/tms/UserTest.java
  18. 5
      src/test/java/com/msdw/tms/service/QuestionsServiceTest.java

@ -139,9 +139,16 @@
<artifactId>hutool-all</artifactId> <artifactId>hutool-all</artifactId>
<version>5.3.8</version> <version>5.3.8</version>
</dependency> </dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.72</version>
</dependency>
</dependencies> </dependencies>
<build> <build>
<finalName>evaluation</finalName>
<plugins> <plugins>
<plugin> <plugin>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>

@ -95,4 +95,11 @@ public interface QuestionsControllerApi {
@ApiOperation(value = "通过excel批量导出", notes = "通过excel批量导出") @ApiOperation(value = "通过excel批量导出", notes = "通过excel批量导出")
void exportQuestion(HttpServletResponse response) throws Exception; void exportQuestion(HttpServletResponse response) throws Exception;
/**
* 通过excel批量导出
*/
@ApiOperation(value = "导出导入失败的数据和失败原因", notes = "导出导入失败的数据和失败原因")
void exportFailureRecord(HttpServletResponse response, String token) throws Exception;
} }

@ -93,8 +93,9 @@ public class Constant {
/** /**
* 测评规则表id * 测评规则表id
*/ */
public static final int EVALUATION_RULES_ID = 1;/** public static final int EVALUATION_RULES_ID = 1;
* 测评规则表id /**
* excel后缀
*/ */
public static final String EXCEL_SUFFIX = ".xlsx"; public static final String EXCEL_SUFFIX = ".xlsx";
/** /**

@ -55,7 +55,7 @@ public class ExcelImportUtil<T> {
} }
Field field = entity.getClass().getDeclaredField("index"); Field field = entity.getClass().getDeclaredField("index");
field.setAccessible(true); field.setAccessible(true);
field.set(entity, rowNum); field.set(entity, rowNum + 1);
list.add(entity); list.add(entity);
} }
} catch (Exception e) { } catch (Exception e) {

@ -1,5 +1,6 @@
package com.msdw.tms.controller; package com.msdw.tms.controller;
import com.msdw.tms.api.PersonalFileControllerApi;
import com.msdw.tms.common.utils.R; import com.msdw.tms.common.utils.R;
import com.msdw.tms.entity.PersonalFileEntity; import com.msdw.tms.entity.PersonalFileEntity;
import com.msdw.tms.entity.vo.PersonalFileVo; import com.msdw.tms.entity.vo.PersonalFileVo;
@ -12,7 +13,7 @@ import java.util.List;
@RestController @RestController
@RequestMapping("tms/personalFile") @RequestMapping("tms/personalFile")
public class PersonalFileController { public class PersonalFileController implements PersonalFileControllerApi {
@Autowired @Autowired
private PersonalFileService personalFileService; private PersonalFileService personalFileService;

@ -1,5 +1,6 @@
package com.msdw.tms.controller; package com.msdw.tms.controller;
import com.msdw.tms.api.ProjectControllerApi;
import com.msdw.tms.common.utils.PageUtils; import com.msdw.tms.common.utils.PageUtils;
import com.msdw.tms.common.utils.R; import com.msdw.tms.common.utils.R;
import com.msdw.tms.entity.ProjectEntity; import com.msdw.tms.entity.ProjectEntity;
@ -21,7 +22,7 @@ import java.util.Map;
*/ */
@RestController @RestController
@RequestMapping("fictitious/project") @RequestMapping("fictitious/project")
public class ProjectController { public class ProjectController implements ProjectControllerApi {
@Autowired @Autowired
private ProjectService projectService; private ProjectService projectService;

@ -19,6 +19,7 @@ import javax.servlet.http.HttpServletResponse;
import java.io.IOException; import java.io.IOException;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.Map;
/** /**
@ -116,9 +117,9 @@ public class QuestionsController implements QuestionsControllerApi {
@PostMapping("/import") @PostMapping("/import")
//@RequiresPermissions("qms:questions:import") //@RequiresPermissions("qms:questions:import")
public R importQuestion(@RequestParam(name = "file") MultipartFile file) throws IOException { public R importQuestion(@RequestParam(name = "file") MultipartFile file) throws IOException {
List<String> list = questionsService.importQuestion(file); Map<String, String> map = questionsService.importQuestion(file);
return R.ok().put("data", list); return R.ok().put("data", map);
} }
/** /**
@ -163,4 +164,10 @@ public class QuestionsController implements QuestionsControllerApi {
questionsService.exportQuestion(response); questionsService.exportQuestion(response);
} }
@Override
@GetMapping("/export_failure")
public void exportFailureRecord(HttpServletResponse response, String token) throws Exception {
questionsService.exportFailureRecord(response, token);
}
} }

@ -2,6 +2,7 @@ package com.msdw.tms.entity.request;
import com.msdw.tms.common.utils.poi.ExcelAttribute; import com.msdw.tms.common.utils.poi.ExcelAttribute;
import lombok.Data; import lombok.Data;
import lombok.ToString;
/** /**
* 试题的基本信息表 * 试题的基本信息表
@ -9,6 +10,7 @@ import lombok.Data;
* @author gongsj * @author gongsj
*/ */
@Data @Data
@ToString
public class QuestionsImportRequest { public class QuestionsImportRequest {
/** /**
* 第几行 * 第几行
@ -65,4 +67,15 @@ public class QuestionsImportRequest {
*/ */
@ExcelAttribute(sort = 9) @ExcelAttribute(sort = 9)
private String answerAnalysis; private String answerAnalysis;
public String toStringForCompare() {
return questionStem +
questionTypeName +
optionA +
optionB +
optionC +
optionD +
optionE +
optionF;
}
} }

@ -15,6 +15,7 @@ public enum CommonCode implements ResultCode {
EXCEL_INVALID(false, 10007, "excel表内容错误!"), EXCEL_INVALID(false, 10007, "excel表内容错误!"),
EVALUATION_TIME_INVALID(false, 10008, "测评时间错误!"), EVALUATION_TIME_INVALID(false, 10008, "测评时间错误!"),
EXCEL_FILE_INVALID(false, 10009, "上传excel文件错误!"), EXCEL_FILE_INVALID(false, 10009, "上传excel文件错误!"),
REPEAT_INEXCEL(false, 10010, "试题在excel表中重复!"),
FAIL(false, 11111, "操作失败!"), FAIL(false, 11111, "操作失败!"),
SERVER_ERROR(false, 99999, "抱歉,系统繁忙,请稍后重试!"); SERVER_ERROR(false, 99999, "抱歉,系统繁忙,请稍后重试!");
//操作是否成功 //操作是否成功

@ -0,0 +1,76 @@
package com.msdw.tms.entity.vo;
import com.msdw.tms.common.utils.poi.ExcelAttribute;
import lombok.Data;
import lombok.ToString;
/**
* 试题的基本信息表
*
* @author gongsj
*/
@Data
@ToString
public class QuestionsImportFailureVO {
/**
* 第几行
*/
private Integer index;
/**
* 题干问题描述
*/
@ExcelAttribute(sort = 0)
private String questionStem;
/**
* 题型
*/
@ExcelAttribute(sort = 1)
private String questionTypeName;
/**
* 选项A
*/
@ExcelAttribute(sort = 2)
private String optionA;
/**
* 选项B
*/
@ExcelAttribute(sort = 3)
private String optionB;
/**
* 选项C
*/
@ExcelAttribute(sort = 4)
private String optionC;
/**
* 选项D
*/
@ExcelAttribute(sort = 5)
private String optionD;
/**
* 选项E
*/
@ExcelAttribute(sort = 6)
private String optionE;
/**
* 选项F
*/
@ExcelAttribute(sort = 7)
private String optionF;
/**
* 正确答案
*/
@ExcelAttribute(sort = 8)
private String answer;
/**
* 答案解析
*/
@ExcelAttribute(sort = 9)
private String answerAnalysis;
/**
* 失败原因
*/
@ExcelAttribute(sort = 10)
private String failureMsg;
}

@ -9,13 +9,12 @@ import com.msdw.tms.entity.request.QuestionsQueryRequest;
import com.msdw.tms.entity.request.QuestionsUpdateRequest; import com.msdw.tms.entity.request.QuestionsUpdateRequest;
import com.msdw.tms.entity.vo.EvaluationVO; import com.msdw.tms.entity.vo.EvaluationVO;
import com.msdw.tms.entity.vo.QuestionsDetailVO; import com.msdw.tms.entity.vo.QuestionsDetailVO;
import com.msdw.tms.entity.vo.QuestionsVO;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import java.io.IOException; import java.io.IOException;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Map;
/** /**
* 记录试题信息 * 记录试题信息
@ -38,7 +37,7 @@ public interface QuestionsService extends IService<QuestionsEntity> {
boolean deleteByIds(List<Integer> asList); boolean deleteByIds(List<Integer> asList);
List<String> importQuestion(MultipartFile file) throws IOException; Map<String, String> importQuestion(MultipartFile file) throws IOException;
FilesResult uploadFiles(MultipartFile file) throws IOException; FilesResult uploadFiles(MultipartFile file) throws IOException;
@ -49,5 +48,7 @@ public interface QuestionsService extends IService<QuestionsEntity> {
void exportQuestion(HttpServletResponse response) throws Exception; void exportQuestion(HttpServletResponse response) throws Exception;
String getEvaluationRemainingTime(Integer userId); String getEvaluationRemainingTime(Integer userId);
void exportFailureRecord(HttpServletResponse response, String token) throws Exception;
} }

@ -72,7 +72,7 @@ public class ProjectRecordServiceImpl extends ServiceImpl<ProjectRecordDao, Proj
FileInputStream fis = new FileInputStream(resource.getFile()); FileInputStream fis = new FileInputStream(resource.getFile());
//3、通过工具类下载文件 //3、通过工具类下载文件
new ExcelExportUtil(ProjectRecordImportRequest.class, Constant.STARTING_ROW, Constant.STYLE_INDEX). new ExcelExportUtil(ProjectRecordImportRequest.class, Constant.ROW_INDEX, Constant.STYLE_INDEX).
export(response, fis, importRequests, "实验报告导出.xlsx"); export(response, fis, importRequests, "实验报告导出.xlsx");
} }

@ -1,6 +1,7 @@
package com.msdw.tms.service.impl; package com.msdw.tms.service.impl;
import cn.hutool.core.date.DateUtil; import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
@ -61,6 +62,7 @@ public class QuestionsServiceImpl extends ServiceImpl<QuestionsDao, QuestionsEnt
StringRedisTemplate stringRedisTemplate; StringRedisTemplate stringRedisTemplate;
private String REMAINING_TINE_KEY = "REMAINING_TINE"; private String REMAINING_TINE_KEY = "REMAINING_TINE";
private String FAILURE_IMPORT_KEY = "FAILURE_IMPORT";
/** /**
* 条件加分页查询题干模糊查询未删除修改时间降序 * 条件加分页查询题干模糊查询未删除修改时间降序
@ -319,10 +321,17 @@ public class QuestionsServiceImpl extends ServiceImpl<QuestionsDao, QuestionsEnt
* 1校验题干重复和题型不对的 * 1校验题干重复和题型不对的
* 2从列表中将该题剔除并记录index和导入失败的原因 * 2从列表中将该题剔除并记录index和导入失败的原因
* 3名称和选项内容都相同的要去重 * 3名称和选项内容都相同的要去重
* 返回数据token成功几条失败几条
* 将失败数据和失败信息保存在redis中使用list类型加上过期时间key是token
*/ */
@Override @Override
@Transactional @Transactional
public List<String> importQuestion(MultipartFile file) throws IOException { public Map<String, String> importQuestion(MultipartFile file) throws IOException {
//准备map接收导入失败的数据信息
Map<String, String> failureRecord = new HashMap<>();
//准备list收集失败数据
List<QuestionsImportFailureVO> failureVOs = new ArrayList<>();
// 参数合法性校验,只能上传.xlsx后缀的文件 // 参数合法性校验,只能上传.xlsx后缀的文件
if (StringUtils.isBlank(file.getOriginalFilename()) if (StringUtils.isBlank(file.getOriginalFilename())
|| !file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")).equals(Constant.EXCEL_SUFFIX)) { || !file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")).equals(Constant.EXCEL_SUFFIX)) {
@ -337,12 +346,28 @@ public class QuestionsServiceImpl extends ServiceImpl<QuestionsDao, QuestionsEnt
ExceptionCast.cast(CommonCode.EXCEL_INVALID); ExceptionCast.cast(CommonCode.EXCEL_INVALID);
} }
List<String> failureRecord = new ArrayList<>(); //去掉重复数据,得到去重后的数据
ArrayList<QuestionsImportRequest> distinctList = list.stream().collect(Collectors.collectingAndThen(// 去重收集
for (int i = 0; i < list.size(); i++) { Collectors.toCollection(() ->
QuestionsImportRequest question = list.get(i); new TreeSet<>(Comparator.comparing(QuestionsImportRequest::toStringForCompare))),
ArrayList::new
));
//与元数据做差,得到重复的数据
List<QuestionsImportRequest> repeatFactor = removeRepeatFactor(distinctList, list);
//记录到失败信息列表
repeatFactor.forEach(question -> {
QuestionsImportFailureVO failureVO = new QuestionsImportFailureVO();
BeanUtils.copyProperties(question, failureVO);
failureVO.setFailureMsg(CommonCode.REPEAT_INEXCEL.message());
failureVOs.add(failureVO);
});
List<QuestionsEntity> questions = distinctList.stream().map(question -> {
//校验题干和内容重复 //校验题干和内容重复
QuestionsEntity questionsEntity = new QuestionsEntity(); QuestionsEntity questionsEntity = new QuestionsEntity();
//属性对拷
BeanUtils.copyProperties(question, questionsEntity); BeanUtils.copyProperties(question, questionsEntity);
String questionTypeName = question.getQuestionTypeName(); String questionTypeName = question.getQuestionTypeName();
//根据题型名称得到题型号 //根据题型名称得到题型号
@ -357,8 +382,11 @@ public class QuestionsServiceImpl extends ServiceImpl<QuestionsDao, QuestionsEnt
questionsEntity.setQuestionType(Constant.QuestionType.TRUE_OR_FALSE.getType()); questionsEntity.setQuestionType(Constant.QuestionType.TRUE_OR_FALSE.getType());
} else { } else {
// 题型不正确 // 题型不正确
failureRecord.add("第 " + question.getIndex() + " 行导入失败," + "题干:" + question.getQuestionStem() + ",失败信息:" + CommonCode.QUESTIONTYPE_INVALID.message()); QuestionsImportFailureVO failureVO = new QuestionsImportFailureVO();
continue; BeanUtils.copyProperties(question, failureVO);
failureVO.setFailureMsg(CommonCode.QUESTIONTYPE_INVALID.message());
failureVOs.add(failureVO);
return null;
} }
//构造根据内容查询试题数量的Wrapper //构造根据内容查询试题数量的Wrapper
@ -367,26 +395,63 @@ public class QuestionsServiceImpl extends ServiceImpl<QuestionsDao, QuestionsEnt
int count = this.count(queryWrapper); int count = this.count(queryWrapper);
if (count > 0) {//说明已存在 if (count > 0) {//说明已存在
failureRecord.add("第 " + question.getIndex() + " 行导入失败," + "题干:" + question.getQuestionStem() + ",失败信息:" + CommonCode.QUESTION_EXISTS.message()); QuestionsImportFailureVO failureVO = new QuestionsImportFailureVO();
continue; BeanUtils.copyProperties(question, failureVO);
failureVO.setFailureMsg(CommonCode.QUESTION_EXISTS.message());
failureVOs.add(failureVO);
return null;
} }
//TODO 创建者和修改者。。。
questionsEntity.setCreateTime(new Date()); questionsEntity.setCreateTime(new Date());
questionsEntity.setModifyTime(new Date()); questionsEntity.setModifyTime(new Date());
return questionsEntity;
}).filter(Objects::nonNull)// 过滤掉为null的对象
.collect(Collectors.toList());
this.save(questionsEntity); String token = "";
// 有导入失败的数据,才会存入redis
if (failureVOs.size() > 0) {
//生成token
token = FAILURE_IMPORT_KEY + UUID.randomUUID().toString().replace("-", "");
ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
String failureVOJson = JSON.toJSONString(failureVOs);
ops.set(token, failureVOJson, 30 * 60, TimeUnit.SECONDS);
} }
// 批量保存
this.saveBatch(questions);
failureRecord.put("token", token);
failureRecord.put("successNum", (list.size() - failureVOs.size()) + "");
failureRecord.put("failureNum", failureVOs.size() + "");
return failureRecord; return failureRecord;
} }
private <T> List<T> removeRepeatFactor(List<T> source, List<T> dest) {
if (source != null && dest != null) {
if (source.size() != 0 && dest.size() != 0) {
Collection<T> A = new ArrayList<>(source);
List<T> B = new ArrayList<>(dest);
A.retainAll(B);
if (A.size() != 0) {
B.removeAll(A);
}
return B;
}
}
return dest;
}
/** /**
* 上传模板文件修改模板信息表数据 * 上传模板文件修改模板信息表数据
*/ */
@Override @Override
@Transactional @Transactional
public FilesResult uploadFiles(MultipartFile file) throws IOException { public FilesResult uploadFiles(MultipartFile file) throws IOException {
// 参数合法性校验,只能上传.xlsx后缀的文件 // 参数合法性校验,只能上传.xlsx后缀的文件
if (StringUtils.isBlank(file.getOriginalFilename()) if (StringUtils.isBlank(file.getOriginalFilename())
|| !file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")).equals(Constant.EXCEL_SUFFIX)) { || !file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")).equals(Constant.EXCEL_SUFFIX)) {
@ -493,12 +558,10 @@ public class QuestionsServiceImpl extends ServiceImpl<QuestionsDao, QuestionsEnt
//3、通过工具类下载文件 //3、通过工具类下载文件
new ExcelExportUtil(QuestionsImportRequest.class, Constant.ROW_INDEX, Constant.STYLE_INDEX). new ExcelExportUtil(QuestionsImportRequest.class, Constant.ROW_INDEX, Constant.STYLE_INDEX).
export(response, fis, list, "试题表.xlsx"); export(response, fis, list, "试题表.xlsx");
} }
@Override @Override
public String getEvaluationRemainingTime(Integer userId) { public String getEvaluationRemainingTime(Integer userId) {
//时长转成秒来计算 //时长转成秒来计算
//先查询该用户有没有开始考试,既redis中有没有跟该用户id相关联的key //先查询该用户有没有开始考试,既redis中有没有跟该用户id相关联的key
//如果没有,表示是开始测评,向redis中插入一条数据,key是前缀加用户id,value是当前时间,过期时间是测评时长加三十秒 //如果没有,表示是开始测评,向redis中插入一条数据,key是前缀加用户id,value是当前时间,过期时间是测评时长加三十秒
@ -526,6 +589,37 @@ public class QuestionsServiceImpl extends ServiceImpl<QuestionsDao, QuestionsEnt
return DateUtil.secondToTime(remainingTime); return DateUtil.secondToTime(remainingTime);
} }
@Override
public void exportFailureRecord(HttpServletResponse response, String token) throws Exception {
if (StringUtils.isEmpty(token)) {
return;
}
ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
//获取数据
String record = ops.get(token);
if (StringUtils.isEmpty(record)) {
return;
}
List<QuestionsImportFailureVO> parse = (List<QuestionsImportFailureVO>) JSON.parse(record);
parse.sort(Comparator.comparing(QuestionsImportFailureVO::getIndex));
// Collections.sort(parse, new Comparator<QuestionsImportFailureVO>() {
// @Override
// public int compare(QuestionsImportFailureVO o1, QuestionsImportFailureVO o2) {
// //升序
// return o1.getIndex().compareTo(o2.getIndex());
// }
// });
//2.加载模板流数据
org.springframework.core.io.Resource resource = new ClassPathResource("excel-template/试题导入失败数据导出模板.xlsx");
FileInputStream fis = new FileInputStream(resource.getFile());
//3、通过工具类下载文件
new ExcelExportUtil(QuestionsImportRequest.class, Constant.ROW_INDEX, Constant.STYLE_INDEX).
export(response, fis, parse, "导入失败数据表.xlsx");
}
private Set<QuestionsVO> getRandomList(int len, List<QuestionsEntity> list) { private Set<QuestionsVO> getRandomList(int len, List<QuestionsEntity> list) {
Set<QuestionsVO> set = new HashSet<>(); Set<QuestionsVO> set = new HashSet<>();
Random random = new Random(); Random random = new Random();

@ -1,6 +1,7 @@
package com.msdw.tms; package com.msdw.tms;
import cn.hutool.core.date.DateUtil; import cn.hutool.core.date.DateUtil;
import com.msdw.tms.entity.request.QuestionsImportRequest;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest;
@ -15,8 +16,9 @@ import java.time.Instant;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.time.ZoneId; import java.time.ZoneId;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
import java.util.Date; import java.util.*;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
@SpringBootTest @SpringBootTest
class TmsApplicationTests { class TmsApplicationTests {
@ -236,4 +238,181 @@ class TmsApplicationTests {
} }
@Test
void t8() {
List<String> list = new ArrayList<>();
list.add("a");
list.add("b");
list.add("c");
list.add("d");
list.add("b");
list.add("c");
list.add("a");
list.add("a");
list.add("a");
System.out.println("\n例子1 - 计算'a'出现的次数");
System.out.println("a : " + Collections.frequency(list, "a"));
System.out.println("\n例子2 - 计算所有对象出现的次数");
Set<String> uniqueSet = new HashSet<>(list);
for (String temp : uniqueSet) {
System.out.println(temp + ": " + Collections.frequency(list, temp));
}
System.out.println("\n例子3 -用Map来计算对象出现的次数");
Map<String, Integer> map = new HashMap<>();
for (String temp : list) {
Integer count = map.get(temp);
map.put(temp, (count == null) ? 1 : count + 1);
}
printMap(map);
System.out.println("\nMap排序-以key排序");
Map<String, Integer> treeMap = new TreeMap<>(map);
printMap(treeMap);
}
static void printMap(Map<String, Integer> map) {
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println("Key-value : " + entry.getKey() + "- "
+ entry.getValue());
}
}
@Test
void t9() throws Exception {
List<UserTest> list = new ArrayList<>();
list.add(new UserTest(1, "张三", "男", "深圳", "123456"));
list.add(new UserTest(2, "李四", "男", "深圳", "123456"));
list.add(new UserTest(3, "张三", "男", "杭州", "123456"));
list.add(new UserTest(4, "张三", "男", "深圳", "123456"));
list.add(new UserTest(5, "王五", "男", "深圳", "123456"));
list.add(new UserTest(6, "张三", "男", "深圳", "123456"));
list.add(new UserTest(7, "赵六", "女", "深圳", "123456"));
list.add(new UserTest(8, "赵六", "女", "深圳", "123456"));
list.add(new UserTest(9, "赵六", "女", "深圳", "123456"));
list.add(new UserTest(10, "赵六", "女", "深圳", "123456"));
list.add(new UserTest(11, "赵六", "女", "深圳", "123456"));
list.add(new UserTest(12, "张三", "男", "菲律宾", "123456"));
list.add(new UserTest(13, "张三", "男", "深圳", "123456"));
list.add(new UserTest(14, "张三", "男", "马来西亚", "123456"));
List<String> errorMsg = new ArrayList<>();
ArrayList<UserTest> collect = list.stream()
.collect(Collectors.collectingAndThen(// 去重收集
Collectors.toCollection(() ->
new TreeSet<>(Comparator.comparing(UserTest::toString))),
ArrayList::new
));
for (UserTest userTest : collect) {
System.out.println(userTest.getIndex() + "-----" + userTest.toString());
}
System.out.println("----------------------------");
List<UserTest> userTests = removeRepeatFactor3(collect, list);
for (UserTest userTest : userTests) {
System.out.println(userTest.getIndex() + "-----" + userTest.toString());
}
}
private List<UserTest> removeRepeatFactor(List<UserTest> list1, List<UserTest> list2) {
if (list1 != null && list2 != null) {
if (list1.size() != 0 && list2.size() != 0) {
Collection<UserTest> A = new ArrayList<>(list1);
List<UserTest> B = new ArrayList<>(list2);
A.retainAll(B);
if (A.size() != 0) {
B.removeAll(A);
}
return B;
}
}
return list2;
}
private <T> List<T> removeRepeatFactor3(List<T> list1, List<T> list2) {
if (list1 != null && list2 != null) {
if (list1.size() != 0 && list2.size() != 0) {
Collection<T> A = new ArrayList<>(list1);
List<T> B = new ArrayList<>(list2);
A.retainAll(B);
if (A.size() != 0) {
B.removeAll(A);
}
return B;
}
}
return list2;
}
public List<String> removeRepeatFactor2(List<String> list1, List<String> list2) throws Exception {
if (list1 != null && list2 != null) {
if (list1.size() != 0 && list2.size() != 0) {
Collection<String> A = new ArrayList<>(list1);
Collection<String> B = new ArrayList<>(list2);
A.retainAll(B);
if (A.size() != 0) {
B.removeAll(A);
}
return (List<String>) B;
}
}
return list2;
}
@Test
void t10() {
QuestionsImportRequest questionsImportRequest = new QuestionsImportRequest();
questionsImportRequest.setOptionA("aaa");
questionsImportRequest.setOptionB("bbb");
questionsImportRequest.setOptionC("ccc");
questionsImportRequest.setOptionD("ddd");
questionsImportRequest.setOptionE("eee");
questionsImportRequest.setOptionF("fff");
questionsImportRequest.setQuestionStem("stem");
questionsImportRequest.setQuestionTypeName("type");
System.out.println(questionsImportRequest.toStringForCompare());
}
@Test
void t11() {
List<UserTest> list = new ArrayList<>();
list.add(new UserTest(1, "张三", "男", "深圳", "123456"));
list.add(new UserTest(2, "李四", "男", "深圳", "123456"));
list.add(new UserTest(3, "张三", "男", "杭州", "123456"));
list.add(new UserTest(4, "张三", "男", "深圳", "123456"));
list.add(new UserTest(5, "王五", "男", "深圳", "123456"));
list.add(new UserTest(6, "张三", "男", "深圳", "123456"));
list.add(new UserTest(7, "赵六", "女", "深圳", "123456"));
list.add(new UserTest(8, "赵六", "女", "深圳", "123456"));
list.add(new UserTest(9, "赵六", "女", "深圳", "123456"));
list.add(new UserTest(10, "赵六", "女", "深圳", "123456"));
list.add(new UserTest(11, "赵六", "女", "深圳", "123456"));
list.add(new UserTest(12, "张三", "男", "菲律宾", "123456"));
list.add(new UserTest(13, "张三", "男", "深圳", "123456"));
list.add(new UserTest(14, "张三", "男", "马来西亚", "123456"));
stringRedisTemplate.opsForList().leftPush("sss", list.toString());
}
} }

@ -0,0 +1,26 @@
package com.msdw.tms;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class UserTest {
private int index;
private String name;
private String gender;
private String addr;
private String phone;
@Override
public String toString() {
return "UserTest{" +
"name='" + name + '\'' +
", gender='" + gender + '\'' +
", addr='" + addr + '\'' +
", phone='" + phone + '\'' +
'}';
}
}

@ -24,6 +24,7 @@ import java.io.IOException;
import java.nio.file.Files; import java.nio.file.Files;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Map;
/** /**
* 记录试题信息 * 记录试题信息
@ -93,9 +94,9 @@ class QuestionsServiceTest {
IOUtils.copy(new FileInputStream(file), fileItem.getOutputStream()); IOUtils.copy(new FileInputStream(file), fileItem.getOutputStream());
MultipartFile multipartFile = new CommonsMultipartFile(fileItem); MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
List<String> strings = questionsService.importQuestion(multipartFile); Map<String, String> map = questionsService.importQuestion(multipartFile);
System.out.println(strings.toString()); System.out.println(map.toString());
} }
@Test @Test

Loading…
Cancel
Save