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的list
11         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中的BeanUtils
16             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找到每個名字對應數量的map
12         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,用anyMatch
21         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_TIME
16         )
17         VALUES
18         <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
@Service
public 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;
    }
}

 

 

後續更新

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章