整理一下常用的代码,可以支持后续的直接拿过来使用,不需要慢慢再去百度搜索了, 后续不间断更新
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;
}
}
10. 使用反射操作对象的List属性
1 public class Reflact {
2 public static void main(String[] args) throws Exception {
3
4 //测试方法
5 List<Room> rooms = new ArrayList<Room>();
6 rooms.add(new Room(1,"大浪",100.0));
7 rooms.add(new Room(2,"xiao浪",101.0));
8 User u =new User("zhangsan", 18, rooms);
9 doWithR(u);
10 }
11 static void doWithR(Object obj) throws Exception{
12 Field[] fields = obj.getClass().getDeclaredFields();
13 for (Field f : fields) {
14 if(!f.isAccessible()){
15 f.setAccessible(true);//赋权使用,否则private类型是无法操作的
16 }
17 if(List.class.isAssignableFrom(f.getType())){//判断是否为list
18 Type t = f.getGenericType();
19 if(t instanceof ParameterizedType){
20 //ParameterizedType pt = (ParameterizedType)t;
21 //Class clz = (Class)pt.getActualTypeArguments()[0];
22 Class clazz = f.get(obj).getClass();//获取对象list属性的class
23 Method m = clazz.getDeclaredMethod("size");//获取list属性的size方法
24 int size = (Integer)m.invoke(f.get(obj));//调用size方法
25 for(int i = 0; i < size; i++){//根据size大小循环
26 Method getM = clazz.getDeclaredMethod("get", int.class);//获取list属性的get方法
27 //System.out.println(getM);
28 Object u = getM.invoke(f.get(obj), i);//调用get方法获取list中的对象
29 doWithR(u);//若list中还有list可以递归调用
30 //测试是否可以获取到list中对象的属性的值
31 Field[] uf = u.getClass().getDeclaredFields();
32 for (Field fu : uf) {
33 if(!fu.isAccessible())
34 fu.setAccessible(true);
35 System.out.println(fu.get(u));
36 }
37 }
38 }
39 }
40 }
41 }
42 }
11. 获取ip的工具类方法
1 /**
2 * IP地址
3 */
4 public class IPUtils {
5
6 private static Logger logger = LoggerFactory.getLogger(IPUtils.class);
7
8 /**
9 * 获取IP地址
10 * 使用Nginx等反向代理软件, 则不能通过request.getRemoteAddr()获取IP地址
11 * 如果使用了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP地址,X-Forwarded-For中第一个非unknown的有效IP字符串,则为真实IP地址
12 */
13 public static String getIpAddr(HttpServletRequest request) {
14 String ip = null;
15 try {
16 ip = request.getHeader("x-forwarded-for");
17 if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
18 ip = request.getHeader("Proxy-Client-IP");
19 }
20 if (StringUtils.isEmpty(ip) || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
21 ip = request.getHeader("WL-Proxy-Client-IP");
22 }
23 if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
24 ip = request.getHeader("HTTP_CLIENT_IP");
25 }
26 if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
27 ip = request.getHeader("HTTP_X_FORWARDED_FOR");
28 }
29 if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
30 ip = request.getRemoteAddr();
31 }
32 } catch (Exception e) {
33 logger.error("IPUtils ERROR ", e);
34 }
35 // 使用代理,则获取第一个IP地址
36 if (StringUtils.isEmpty(ip) && ip.length() > 15) {
37 if (ip.indexOf(",") > 0) {
38 ip = ip.substring(0, ip.indexOf(","));
39 }
40 }
41 return ip;
42 }
43 }
12. 获取当前方法的名字
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
13. 使用nio进行文件的快速拷贝
public static void fileCopy( File in, File out )
throws IOException
{
FileChannel inChannel = new FileInputStream( in ).getChannel();
FileChannel outChannel = new FileOutputStream( out ).getChannel();
try
{
// inChannel.transferTo(0, inChannel.size(), outChannel); // original -- apparently has trouble copying large files on Windows
// magic number for Windows, 64Mb - 32Kb)
int maxCount = (64 * 1024 * 1024) - (32 * 1024);
long size = inChannel.size();
long position = 0;
while ( position < size )
{
position += inChannel.transferTo( position, maxCount, outChannel );
}
}
finally
{
if ( inChannel != null )
{
inChannel.close();
}
if ( outChannel != null )
{
outChannel.close();
}
}
}
14.创建文件的缩略图
1 private void createThumbnail(String filename, int thumbWidth, int thumbHeight, int quality, String outFilename)
2 throws InterruptedException, FileNotFoundException, IOException
3 {
4 // load image from filename
5 Image image = Toolkit.getDefaultToolkit().getImage(filename);
6 MediaTracker mediaTracker = new MediaTracker(new Container());
7 mediaTracker.addImage(image, 0);
8 mediaTracker.waitForID(0);
9 // use this to test for errors at this point: System.out.println(mediaTracker.isErrorAny());
10
11 // determine thumbnail size from WIDTH and HEIGHT
12 double thumbRatio = (double)thumbWidth / (double)thumbHeight;
13 int imageWidth = image.getWidth(null);
14 int imageHeight = image.getHeight(null);
15 double imageRatio = (double)imageWidth / (double)imageHeight;
16 if (thumbRatio < imageRatio) {
17 thumbHeight = (int)(thumbWidth / imageRatio);
18 } else {
19 thumbWidth = (int)(thumbHeight * imageRatio);
20 }
21
22 // draw original image to thumbnail image object and
23 // scale it to the new size on-the-fly
24 BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB);
25 Graphics2D graphics2D = thumbImage.createGraphics();
26 graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
27 graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null);
28
29 // save thumbnail image to outFilename
30 BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(outFilename));
31 JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
32 JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbImage);
33 quality = Math.max(0, Math.min(quality, 100));
34 param.setQuality((float)quality / 100.0f, false);
35 encoder.setJPEGEncodeParam(param);
36 encoder.encode(thumbImage);
37 out.close();
38 }