位置: IT常识 - 正文
推荐整理分享java常用代码整理(java 代码简洁),希望有所帮助,仅作参考,欢迎阅读内容。
文章相关热门搜索词:一段java代码的详细解说,java示例代码,java常用的代码,java示例代码,java常用的代码,java代码例子讲解,java代码例子讲解,java代码例子讲解,内容如对您有帮助,希望把文章链接给更多的朋友!
整理一下常用的代码,可以支持后续的直接拿过来使用,不需要慢慢再去百度搜索了, 后续不间断更新
1.List转List
将一个类型的List转为另一个类型的List
1 public static void main(String[] args) { 2 List<TbUser> userList = Lists.newArrayList(); 3 TbUser user = new TbUser(); 4 user.setId(1).setName("小王").setTel("12345"); 5 TbUser user2 = new TbUser(); 6 user2.setId(1).setName("小李").setTel("56789"); 7 userList.add(user); 8 userList.add(user2); 9 10 //1.转为name的list11 List<String> nameList = userList.stream().map(TbUser::getName).collect(Collectors.toList());12 //2.转为另外一种对象的集合13 List<TestUser> testUserList = userList.stream().map(u -> {14 TestUser testUser = new TestUser();15 //使用spring中的BeanUtils16 BeanUtils.copyProperties(u, testUser);17 return testUser;18 }).collect(Collectors.toList());19 }2.List转Map
一般用于将数据库中的一部分数据取出来,然后转为map,方便后续的操作
1 public static void main(String[] args) { 2 List<TbUser> userList = Lists.newArrayList(); 3 TbUser user = new TbUser(); 4 user.setId(1).setName("小王").setTel("12345"); 5 TbUser user2 = new TbUser(); 6 user2.setId(1).setName("小李").setTel("56789"); 7 userList.add(user); 8 userList.add(user2); 9 10 11 //1.将userList转为Map<Integer,TbUser>, 前提是userList中key不重复12 Map<Integer, TbUser> map = userList.stream().collect(Collectors.toMap(TbUser::getId, u -> u));13 //2. 将userList转为Map<Integer,String>,前提是userList中key不重复14 Map<Integer, String> map2 = userList.stream().collect(Collectors.toMap(TbUser::getId, TbUser::getTel));15 //3. 将userList转为Map<Integer,TbUser>,userList中key重复的话,后一个覆盖前面一个16 Map<Integer, TbUser> map3 = userList.stream().collect(Collectors.toMap(TbUser::getId, Function.identity(), (key1, key2) -> key2));17 18 }3. List重复校验
1 public static void main(String[] args) { 2 List<TbUser> userList = Lists.newArrayList(); 3 TbUser user = new TbUser(); 4 user.setId(1).setName("小王").setTel("12345"); 5 TbUser user2 = new TbUser(); 6 user2.setId(1).setName("小李").setTel("56789"); 7 userList.add(user); 8 userList.add(user2); 9 10 11 //1.从userList找到每个名字对应数量的map12 Map<String, Long> countMap = userList.stream().collect(Collectors.groupingBy(TbUser::getName, Collectors.counting()));13 //2. 找到存在重复的名字,只需要遍历countMap的key,然后根据key再从countMap找到值大于1的就行了14 List<String> repeatNameList = countMap.keySet().stream().filter(key -> countMap.get(key) > 1).collect(Collectors.toList());15 //3.如果要对userList中去除名字和性别同时都相同的人, 如果只是简单的List<String>去重,可以直接使用distinct()16 List<TbUser> uniqueList = userList.stream().collect(17 Collectors. collectingAndThen(18 Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.getName() + "-" + o.getSex()))), ArrayList::new)19 );20 //4. 只是想看看List中是否包含一个名字叫做“小王”的人, 如果想返回user对象就用filter,如果只返回true和false,用anyMatch21 boolean anyMatch = userList.stream().anyMatch(u -> Objects.equals(u.getName(), "小王"));22 }4.List中先分组,然后多次排序
通常对List处理的时候,肯定有分组的,再分组之后,对每一组数据首先对A字段排序,然后对B字段进行排序
1 public static void main(String[] args) { 2 List<TbUser> userList = Lists.newArrayList(); 3 TbUser user = new TbUser(); 4 user.setId(1).setName("小王").setTel("12345"); 5 TbUser user2 = new TbUser(); 6 user2.setId(2).setName("小李").setTel("56789"); 7 TbUser user3 = new TbUser(); 8 user3.setId(3).setName("小李").setTel("56789"); 9 userList.add(user);10 userList.add(user2);11 userList.add(user3);12 13 //1. 根据集合中名字进行分组14 Map<String, List<TbUser>> usernameGroupMap = userList.stream().collect(Collectors.groupingBy(TbUser::getName));15 //2. 按照名字分组之后,每一组根据电话号码进行从小到大排序, 顺序16 HashMap<String, List<TbUser>> groupThenOrderByIdAscMap = userList.stream()17 .collect(Collectors.groupingBy(TbUser::getName,18 HashMap::new,19 Collectors.collectingAndThen(Collectors.toList(),20 list -> list.stream()21 .sorted(Comparator.comparing(TbUser::getTel))22 .collect(Collectors.toList()))));23 //3. 按照名字分组之后,每一组根据电话号码进行从大到小排序, 也就是逆序, 和上一个相比,就是多了一个reversed()24 HashMap<String, List<TbUser>> groupThenOrderByIdDescMap = userList.stream()25 .collect(Collectors.groupingBy(TbUser::getName,26 HashMap::new,27 Collectors.collectingAndThen(Collectors.toList(),28 list -> list.stream()29 .sorted(Comparator.comparing(TbUser::getTel).reversed())30 .collect(Collectors.toList()))));31 32 //4, 按照名字分组之后,然后先根据i根据电话号码进行从小到大排序, 号码一样的再根据id从小到大排序33 HashMap<String, List<TbUser>> ordersMap = userList.stream()34 .collect(Collectors.groupingBy(TbUser::getName,35 HashMap::new,36 Collectors.collectingAndThen(Collectors.toList(),37 list -> list.stream()38 .sorted(Comparator.comparing(TbUser::getTel)39 .thenComparing(TbUser::getId))40 .collect(Collectors.toList()))));41 }5. excel导出的时候,设置序列,实现的效果如下所示,还有其他的一些数据校验
1 //设置数字范围 2 public void excelRuleNumberBetween(Sheet sheet, int min, int max, int firstRow, int lastRow, int firstCol, int lastCol){ 3 DataValidationHelper helper = sheet.getDataValidationHelper(); 4 CellRangeAddressList addressList = new CellRangeAddressList(firstRow, lastRow, firstCol, lastCol);//设置行列范围 5 //设置数据 6 DataValidationConstraint constraint = helper.createIntegerConstraint(DataValidationConstraint.OperatorType.BETWEEN, 7 String.valueOf(min),String.valueOf(max)); 8 DataValidation dataValidation = helper.createValidation(constraint, addressList); 9 dataValidation.createErrorBox("输入值类型或大小有误", String.format("请输入%s~%s之间的数值",min,max));10 //处理Excel兼容性问题11 if(dataValidation instanceof XSSFDataValidation) {12 dataValidation.setSuppressDropDownArrow(true);13 dataValidation.setShowErrorBox(true);14 }else {15 dataValidation.setSuppressDropDownArrow(false);16 }17 sheet.addValidationData(dataValidation);18 }19 20 21 //设置校验序列22 public void excelRuleSelect(Sheet sheet, String[] rule, int firstRow, int lastRow, int firstCol, int lastCol) {23 DataValidationHelper helper = sheet.getDataValidationHelper();24 CellRangeAddressList addressList = new CellRangeAddressList(firstRow, lastRow, firstCol, lastCol);25 DataValidationConstraint constraint = helper.createExplicitListConstraint(rule);26 DataValidation dataValidation = helper.createValidation(constraint, addressList);27 dataValidation.createErrorBox("输入有误", "请选择下拉参数");28 if (dataValidation instanceof XSSFDataValidation) {29 dataValidation.setSuppressDropDownArrow(true);30 dataValidation.setShowErrorBox(true);31 } else {32 dataValidation.setSuppressDropDownArrow(false);33 }34 35 sheet.addValidationData(dataValidation);36 }37 38 39 //列数据每个数据唯一40 public void excelRuleUniqueue(Sheet sheet, int firstRow, int lastRow, int firstCol, int lastCol) {41 Row row = sheet.getRow(0);42 Cell cell = row.getCell(firstCol);43 String r = ((XSSFCell) cell).getCTCell().getR();44 r = r.substring(0, 1);45 DataValidationHelper helper = sheet.getDataValidationHelper();46 CellRangeAddressList addressList = new CellRangeAddressList(firstRow, lastRow, firstCol, lastCol);47 //唯一48 DataValidationConstraint constraint = helper.createCustomConstraint(MessageFormat.format("COUNTIF({0}:{0},{0}2)=1",r));49 DataValidation dataValidation = helper.createValidation(constraint, addressList);50 dataValidation.createErrorBox("错误:", "赋值属性列不允许重复");51 dataValidation.setShowErrorBox(true);52 dataValidation.setEmptyCellAllowed(true);53 dataValidation.setSuppressDropDownArrow(true);54 dataValidation.setShowPromptBox(true);55 dataValidation.setErrorStyle(DataValidation.ErrorStyle.STOP);56 57 sheet.addValidationData(dataValidation);58 }6. springboot项目文件上传的单元测试
有的时候单元测试比直接用postman等工具方便点,看实际的情况
1 //单元测试,Excel上传: 2 //@Autowired 3 TestUploadController testUploadController; 4 5 @Test 6 public void uploadStayOutTest() throws Exception { 7 8 File file = new File("C:\\Users\\c\\Downloads\\测试文件导入.xlsx"); 9 FileInputStream fileInputStream = new FileInputStream(file);10 MockMultipartFile multipartFile = new MockMultipartFile(file.getName(), file.getName(),11 ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);12 WageOrderInfoRequestDto infoDto = new WageOrderInfoRequestDto();13 infoDto.setIncmType(1);14 infoDto.setBusiYm("201906");15 infoDto.setWageDate("20190614");16 infoDto.setChangeFlag(2);17 infoDto.setEmpName("张三");18 infoDto.setIdCode("1304211989707080323");19 infoDto.setProbDesc("");20 infoDto.setRemark("验证");21 infoDto.setWageReaSendDate(DateUtil.getDate(new Date()));22 testUploadController.uploadStayOut(multipartFile,infoDto);23 24 }7. mybatis xml文件使用foreach实现批量更新
如果多笔数据的字段都要更新一样的,就没必要用下面这种方式,去掉<trim>直接写setxxx=#{xxx}就行了
<update id="updateBatch" parameterType="java.util.List"> update mydata_table <trim prefix="set" suffixOverrides=","> <trim prefix="status =case" suffix="end,"> <foreach collection="list" item="item" index="index"> <if test="item.status !=null "> when id=#{item.id} then #{item.status} </if> </foreach> </trim> </trim> where id in <foreach collection="list" index="index" item="item" separator="," open="(" close=")"> #{item.id,jdbcType=BIGINT} </foreach> </update>8. mybatis的xml中批量新增
1 <insert id="insertList" parameterType="java.util.List"> 2 insert into t_enterprise_water_ele 3 ( 4 WATER_ELE_ID, 5 ENTERPRISE_ID, 6 ENTERPRISE_USCC, 7 ENTERPRISE_NAME, 8 YEARMONTH, 9 WATER_SIZE,10 WATER_AMOUNT,11 ELE_SIZE,12 ELE_AMOUNT,13 STATUS,14 OPERATOR,15 OPERATE_TIME16 )17 VALUES18 <foreach collection="list" item="item" index="index" separator=",">19 (20 #{item.waterEleId,jdbcType=VARCHAR},21 #{item.enterpriseId,jdbcType=VARCHAR},22 #{item.enterpriseUscc,jdbcType=VARCHAR},23 #{item.enterpriseName,jdbcType=VARCHAR},24 #{item.yearmonth,jdbcType=VARCHAR},25 #{item.waterSize,jdbcType=DECIMAL},26 #{item.waterAmount,jdbcType=VARCHAR},27 #{item.eleSize,jdbcType=DOUBLE},28 #{item.eleAmount,jdbcType=VARCHAR},29 #{item.status,jdbcType=INTEGER},30 #{item.operator,jdbcType=VARCHAR},31 #{item.operateTime,jdbcType=TIMESTAMP}32 )33 </foreach>34 </insert>9 使用mybatis-plus进行单表查询/更新
尽量使用LambdaQueryWrapper/LambdaUpdateWrapper 去做条件拼接,这样拼接条件的key使用的是类似TestUser::getAge的方式,减少硬编码,防止直接写字符串“age”拼错了,要排查好半天
@Slf4j@Servicepublic class TestUserServiceImpl extends ServiceImpl<TestUserMapper, TestUser> implements TestUserService { @Override public String testMethod() { String userName = "王"; Integer age = 18; LambdaQueryWrapper<TestUser> queryWrapper = Wrappers.<TestUser>lambdaQuery() .eq(TestUser::getAge, age) .like(StringUtils.isNotBlank(userName),TestUser::getUserNmae, userName);//%王% List<TestUser> userList = list(queryWrapper); //做后续处理 return null; }}后续更新
上一篇:2022年代表着国内谷歌翻译已经退出了历史舞台,谷歌似乎已经全部禁用国内谷歌翻译-OK源码中国(2022年我们国家将举行什么样的盛会)
下一篇:如何在控制台打印彩色文字-你不知道的ANSI Color(如何在控制台打印debug里的数据)
友情链接: 武汉网站建设