美文网首页
Java 实用方法

Java 实用方法

作者: 潜心之力 | 来源:发表于2018-11-17 23:12 被阅读0次
    List集合随机排序
    int size = list.size();
    Random random = new Random();
    
    for(int i = 0; i < size; i++) { -> 方式一
      int randomPos = random.nextInt(size);
      T temp = list.get(i);
      list.set(i, list.get(randomPos));
      list.set(randomPos, temp);
    }
     
    for(int i = 0; i < size; i++) { -> 方式二
      int randomPos = random.nextInt(size);
      Collections.swap(list, i, randomPos);
    }
    
    Collections.shuffle(list); -> 方式三
    
    list.retainAll(LIST); -> 获取两个集合的交集
    list.removeAll(LIST); -> 获取两个集合的差集
    list.addAll(LIST); -> 获取两个集合的并集
    removeAll + addAll = 无重复并集
    
    验证手机号
    private boolean isPhoneNumber(String phone) {
      String regex = "^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\\d{8}$";
      return phone.matches(regex);
    }
    
    验证密码
    private boolean isPassword(String str) {
      String regex = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,18}$"; 
      return str.matches(regex) && str.length() >= 6 && str.length() <= 18;
    }
    
    字符串编码和解码
    public static String UrlEncode(String content){
       try { -> Json字符串存入Cookie前需要编码
        return URLEncoder.encode(content,"UTF-8");
      } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        return "";
      }
    }
    
    public static String UrlDecode(String content){
       try { -> Json字符串从Cookie中取出时需要解码
        return URLDecoder.decode(content,"UTF-8");
      } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
      return "";
      }
    }
    
    UNICODE和中文互转
    public static String decodeUnicode(String unicode) {
        StringBuffer sb = new StringBuffer();
        String[] hex = unicode.split("\\\\u",-1); -> 默认忽略空字符串,消除默认
        for (int i = 1; i < hex.length; i++) {
            int data = Integer.parseInt(hex[i], 16);
            sb.append((char) data);
        }
        return sb.toString();
    }
    
    public static String decodeUnicode2(String unicode) {
        int start = 0;
        int end = 0;
        final StringBuffer buffer = new StringBuffer();
        while (start > -1) {
            end = unicode.indexOf("\\u", start + 2);
            String charStr = null;
            if (end == -1) {
                charStr = unicode.substring(start + 2, unicode.length());
            } else {
                charStr = unicode.substring(start + 2, end);
            }
            char letter = (char) Integer.parseInt(charStr, 16);
            buffer.append(new Character(letter).toString());
            start = end;
        }
        return buffer.toString();
    }
    
    public static String decodeUnicode3(String unicode) {
        String[] strs = unicode.split("\\\\u",-1);
        String returnStr = "";
        for (int i = 1; i < strs.length; i++) {
            returnStr += (char) Integer.valueOf(strs[i], 16).intValue();
        }
        return returnStr;
    }
    
    private static String encodeUnicode(String content) {
        char[] chars = content.toCharArray();
        String returnStr = "";
        for (int i = 0; i < chars.length; i++) {
            returnStr += "\\u" + Integer.toString(chars[i], 16);
        }
        return returnStr;
    }
    
    显示具体时间
    public static String showTime(Date date) {
        String r = "";
        if (date == null) return r;
        long nowTimeLong = System.currentTimeMillis();
        long currTimeLong = date.getTime();
        long result = Math.abs(nowTimeLong - currTimeLong);
    
        if (result < 60000) { -> 一分钟内
            long seconds = result / 1000;
            if (seconds == 0) {
                r = "刚刚";
            } else {
                r = seconds + "秒前";
            }
        } else if (result >= 60000 && result < 3600000) { -> 一小时内
            long seconds = result / 60000;
            r = seconds + "分钟前";
        } else if (result >= 3600000 && result < 86400000) { -> 一天内
            long seconds = result / 3600000;
            r = seconds + "小时前";
        } else if (result >= 86400000 && result < 1702967296) { -> 三十天内
            long seconds = result / 86400000;
            r = seconds + "天前";
        } else { -> 日期格式
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            r = format.format(date);
        }
        return r;
    }
    
    生成随机订单号
    public static String generateOrderNumber() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String date = sdf.format(new Date());
        int index = (int) ((Math.random() * 9 + 1) * 1000);
        return "wjx_" + date + index;
    }
    
    集合中把相同元素归类并统计个数
    List<Goods> real = new ArrayList<>(); -> 最终结果
    List<Goods> cache = new ArrayList<>(); -> 缓存已有元素
    int total = 0; -> 统计个数
    for (int i = 0; i < goodsList.size(); i++) {
        Goods goods = goodsList.get(i);
        if (!cache.contains(goods)) {
            cache.add(goods);
            goods.setPresentCount(Collections.frequency(goodsList, goods));
            total += goods.getPresentCount();
            real.add(goods);
        }
    }
    
    BigDecimal的使用
    MathContext context = new MathContext(3, RoundingMode.HALF_UP); -> 保留三位有效数字
    BigDecimal decimal = new BigDecimal("1.23", context); -> 推荐使用字符串构建
    
    public BigDecimal add(BigDecimal decimal1, BigDecimal decimal2) { -> 加法
        return decimal1.add(decimal2);
    }
    
    public BigDecimal subtract(BigDecimal decimal1, BigDecimal decimal2) { -> 减法
        return decimal1.subtract(decimal2);
    }
    
    public BigDecimal multiply(BigDecimal decimal1, BigDecimal decimal2) { -> 乘法
        return decimal1.multiply(decimal2);
    }
    
    public BigDecimal divide(BigDecimal decimal1, BigDecimal decimal2
    , int scale, int mode) { -> 除法(除不尽会抛出异常需设置保留位数)
        return decimal1.divide(decimal2, scale, mode); -> 设置保留位数和取舍模式
    }
    
    public BigDecimal scale(BigDecimal decimal,int scale,int mode) { -> 设置精度
        return decimal.setScale(scale,mode);
    }
    
    decimal1.compareTo(decimal2); -> 比较大小
    a = -1 , 表示decimal1小于decimal2;
    a = 0 , 表示decimal1等于decimal2;
    a = 1 , 表示decimal1大于decimal2;
    
    DecimalFormat format = new DecimalFormat("0.00"); -> 自动补零
    DecimalFormat format = new DecimalFormat("#.##"); -> 省略零
    DecimalFormat format = new DecimalFormat("0"); -> 取整
    format.format(total); -> 格式化Decimal
    
    RoundingMode -> 精度取舍模式
    BigDecimal straight = new BigDecimal("1.234567890"); -> 正数
    BigDecimal burden = new BigDecimal("-1.234567890"); -> 负数
    
    BigDecimal.ROUND_UP -> 被舍去部分大于零则进一位
    straight = straight.setScale(8,BigDecimal.ROUND_UP); -> 1.23456789
    straight = straight.setScale(1,BigDecimal.ROUND_UP); -> 1.3
    burden = burden.setScale(8,BigDecimal.ROUND_UP); -> -1.23456789
    burden = burden.setScale(1,BigDecimal.ROUND_UP); -> -1.3
    
    BigDecimal.ROUND_DOWN -> 被舍去部分不进位
    straight = straight.setScale(1,BigDecimal.ROUND_DOWN); -> 1.2
    burden = burden.setScale(1,BigDecimal.ROUND_DOWN); -> -1.2
    
    BigDecimal.ROUND_CEILING -> 向正无穷大舍入,值始终增大
    straight = straight.setScale(8,BigDecimal.ROUND_CEILING); -> 1.23456789
    straight = straight.setScale(1,BigDecimal.ROUND_CEILING); -> 1.3
    burden = burden.setScale(8,BigDecimal.ROUND_CEILING); -> -1.23456789
    burden = burden.setScale(1,BigDecimal.ROUND_CEILING); -> 1.2
    
    BigDecimal.ROUND_FLOOR -> 向负无穷小舍入,值始终减少
    straight = straight.setScale(1,BigDecimal.ROUND_FLOOR); -> 1.2
    burden = burden.setScale(1,BigDecimal.ROUND_FLOOR); -> -1.3
    
    BigDecimal.ROUND_HALF_UP -> 四舍五入
    straight = straight.setScale(2,BigDecimal.ROUND_HALF_UP); -> 1.23
    straight = straight.setScale(3,BigDecimal.ROUND_HALF_UP); -> 1.235
    burden = burden.setScale(2,BigDecimal.ROUND_HALF_UP); -> -1.23
    burden = burden.setScale(3,BigDecimal.ROUND_HALF_UP); -> -1.235
    
    BigDecimal.ROUND_HALF_DOWN -> 五舍六入(大于0.5)
    straight = straight.setScale(2,BigDecimal.ROUND_HALF_DOWN); -> 1.23
    straight = straight.setScale(3,BigDecimal.ROUND_HALF_DOWN); -> 1.235
    burden = burden.setScale(2,BigDecimal.ROUND_HALF_DOWN); -> -1.23
    burden = burden.setScale(3,BigDecimal.ROUND_HALF_DOWN); -> -1.235
    
    BigDecimal.ROUND_HALF_EVEN -> 银行家舍入法[四舍六入]
    五分两种情况[精度末尾奇数(ROUND_HALF_UP)][(精度末尾奇数ROUND_HALF_DOWN)]
    straight = straight.setScale(2,BigDecimal.ROUND_HALF_EVEN); -> 1.23
    straight = straight.setScale(3,BigDecimal.ROUND_HALF_EVEN); -> 1.235
    straight = straight.setScale(4,BigDecimal.ROUND_HALF_EVEN); -> 1.2346
    burden = burden.setScale(2,BigDecimal.ROUND_HALF_EVEN); -> -1.23
    burden = burden.setScale(3,BigDecimal.ROUND_HALF_EVEN); -> -1.235
    burden = burden.setScale(4,BigDecimal.ROUND_HALF_EVEN); -> -1.2346
    
    BigDecimal.ROUND_UNNECESSARY -> 不进行取舍,设置精度将抛出异常
    
    隐藏敏感信息
    StringBuilder builder = new StringBuilder(name.substring(0, 1));
    builder.append("***");
    builder.append(name.substring(name.length() - 2));
    user.setName(builder.toString());
    
    两个变量互换值
    public void exchange(int a,int b){
        a = a+b;
        b = a-b;
        a = a-b;
    }
    
    输出0~1000,不使用循环和条件
    public void print(int i){
        System.out.println(i);
        i = i/(1000-i); -> 递归终止条件
        print(i+1); -> 执行递归
    }
    
    换行串联文本
    public static String connection(String... strings) {
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < strings.length; i++) {
            builder.append(strings[i]);
            if(i != strings.length-1){
                builder.append("\\r\\n");
            }
        }
        return builder.toString();
    }
    
    对象属性非空校验
    private Map<String,Object> validate(Object object, List<String> list) throws Exception {
        Map<String, Object> map = new HashMap<>();
        BeanInfo beanInfo = Introspector.getBeanInfo(object.getClass(), object.getClass().getSuperclass());
        PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
        for (int i = 0; i < descriptors.length; i++) {
            String propertyName = descriptors[i].getName();
            Method method = descriptors[i].getReadMethod();
            Object propertyValue = method.invoke(object);
            if (list.contains(propertyName)) {
                if (StringUtils.isEmpty(propertyValue)) {
                    map.put("msg",propertyName +" is null");
                    return map;
                }
            } else {
                if (propertyValue == null) {
                    map.put("msg",propertyName +" is null");
                    return map;
                }
            }
        }
        return map;
    }
    
    User user = new User(1,"wjx",null);
    List<String> columns = Arrays.asList("id", "name" , "age");
    Map<String,Object> map = validate(user,columns);
    

    相关文章

      网友评论

          本文标题:Java 实用方法

          本文链接:https://www.haomeiwen.com/subject/zieyzftx.html