Java实用小“算法”(持续更新...)

这篇博客涵盖了Java编程中的数字转换、字符串操作、数组处理、日期转换、百分比计算等多个实用技巧。包括将数字转汉字、获取系统用户名、检查字符串是否包含字母、统计字符频率、实现字符串“阶乘式”拆分、比较BigDecimal、字符串倒序、数组元素交换、快速打印数组、字符串日期转换、计算百分比、BigDecimal保留小数等常见操作,展示了Java在数据处理方面的强大能力。

回首向来萧瑟处,归去,也无风雨也无晴。

将字符串中的数字转换为汉字。

    /**
     * 将字符串中的数字转换为汉字(如A3、B5->A三、B五)。
     * @param text
     * @return
     */
    public static String numToChinese(String text){
        for (int i = 0; i < 10; i++) {
            text = text.replace((char) ('0' + i), "零一二三四五六七八九".charAt(i));
        }
        return text;
    }

获取当前系统用户名称。

    /**
     * 获取当前系统用户名称。
     */
    private void windowsUser(){
        //Windows当前用户名。
        String userName = System.getProperty("user.name");
        System.out.println(userName);
    }

判断字符串中是否包含字母。

    /**
     * 判断字符串中是否包含字母。
     * @param str
     * @return
     */
    public static boolean strIsIncludeLetter(String str) {
        String regex = ".*[a-zA-Z]+.*";
        Matcher m = Pattern.compile(regex).matcher(str);
        return m.matches();
    }

统计一个字符串中每个字符出现的次数。

    /**
     * 统计一个字符串中每个字符出现的次数。
     */
    public static void countCahrNum (String str) {
        //将字符串转换为字符数组。
        char[] arrStr = str.toCharArray();
        Map<Character,Integer> counts=new HashMap<Character, Integer>();
        for(char c:arrStr) {
            //遍历字符数组,第一次遍历得到时将其数量为1,再次遍历时数量自增。
            Integer count=counts.get(c);
            if(count==null) {
                counts.put(c, 1);
            }else {
                counts.put(c, count+1);
            }
        }
        //遍历Map输出。
        for(Map.Entry<Character, Integer> entry:counts.entrySet()) {
            System.out.println(entry.getKey()+"-->"+entry.getValue());
        }
    }

将字符串“阶乘式”拆分(123->1 12 123)。

    /**
     * 将字符串“阶乘式”拆分(123->1 12 123)。
     * @param text
     * @return
     */
    public static String wordsEgmentation(String text){
        //使用StringBuilder效率更高。
        int len=text.length();
        StringBuilder stringBuilder = new StringBuilder(len*2);
        for(int i = 1; i <= len; i++){
            //遍历出来的数据,用空格隔开。
            stringBuilder.append(text.substring(0,i));
            //去除末尾的空格。
            if (i<len){
                stringBuilder.append(" ");
            }
        }
        String handleText = stringBuilder.toString();
        return handleText;
    }

比较两个BigDecimal类型数据大小。

    /**
     * 比较两个BigDecimal类型数据大小。
     * @param bigDecimalone
     * @param bigDecimaltwo
     * @return
     */
    public static boolean compareBigDecimal(BigDecimal bigDecimalone,BigDecimal bigDecimaltwo){
        if (bigDecimalone.compareTo(bigDecimaltwo) <= 0){
            System.out.println("前一个数字小于等于后一个数字。");
            return false;
        }else if (bigDecimalone.compareTo(bigDecimaltwo) >= 0){
            System.out.println("前一个数字大于等于后一个数字。");
            return true;
        }
        //返回何值无妨,必然会被其上条件拦截。
        return true;
    }

将字符串倒序输出。

    /**
     * 将字符串倒叙输出(1234->4321)。
     * @param str
     */
    public static void reverseString (String str){
        StringBuffer stringBuffer = new StringBuffer (str);
        System.out.print(stringBuffer.reverse());
    }

交换数组中指定下标元素。

    /**
     * 交换数组中指定下标元素。
     * @param arr
     * @param i
     * @param j
     */
    public static void exchangeElement(int[] arr, int i, int j){
        int tmp=arr[i];
        arr[i]=arr[j];
        arr[j]=tmp;
    }

快速打印数组。

    /**
     * 快速打印数组。
     */
    public static void printArray(){
        int[] arr = {1,2,3};
        System.out.println(Arrays.toString(arr));
    }

将String类型时间转化为Date类型。

    /**
     * 将String类型时间转化为Date类型。
     * @return
     * @throws ParseException
     */
    public static Date string2Date() throws ParseException {
        String dateStr = "2020-10-30 12:00:00";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
        return simpleDateFormat.parse(dateStr);
    }

int类型除法保留两位小数/求百分比(结果四舍五入,保留两位小数)。

    /**
     * int类型除法保留两位小数/求百分比(表明四舍五入,保留两位小数)。
     * @return
     */
    public static void percentResult(){
        int openCount = 3;
        int passCount = 2;
        double result = (double)passCount/openCount*100;
        BigDecimal bigDecimal = new BigDecimal(result);
        String percent = bigDecimal.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue() +"%";
        System.out.println(percent);
    }

BigDecimal类型保留两位小数。

    /**
     * BigDecimal类型保留两位小数。
     */
    public static void bigDecimalKeepTwoDecimalPlaces(){
        BigDecimal bigDecimal = new BigDecimal("3.1415926");
        BigDecimal setScale = bigDecimal.setScale(2,BigDecimal.ROUND_DOWN);
        System.out.println(setScale);
    }

参数定义
ROUND_CEILING 向正无穷方向舍入 。
ROUND_DOWN 向零方向舍入 。
ROUND_FLOOR 向负无穷方向舍入 。
ROUND_HALF_DOWN 向(距离)最近的一边舍入,除非两边(的距离)是相等,如果是这样,向下舍入, 例如1.55 保留一位小数结果为1.5。
ROUND_HALF_EVEN 向(距离)最近的一边舍入,除非两边(的距离)是相等,如果是这样,如果保留位数是奇数,使用ROUND_HALF_UP,如果是偶数,使用ROUND_HALF_DOWN。
ROUND_HALF_UP 向(距离)最近的一边舍入,除非两边(的距离)是相等,如果是这样,向上舍入, 1.55保留一位小数结果为1.6。
ROUND_UNNECESSARY 计算结果是精确的,不需要舍入模式。
ROUND_UP 向远离0的方向舍入。

String数组、List相互转换。

    /**
     *String数组、List转换。
     */
    public static void exchange(){
        /*List转String数组*/
        List<String> listA = new ArrayList<String>();
        listA.add("A");
        listA.add("B");
        String[] toArr = listA.toArray(new String[listA.size()]);
        /*String数组转List*/
        String[] arr = new String[] {"A", "B"};
        List<String> listB = Arrays.asList(arr);
    }

生成指定范围随机数。

    /**
     * 生成指定范围随机数[min,max]。
     * @param min
     * @param max
     * @return
     */
    public static int rangeRandom(int min,int max){
        int randomNum = new Random().nextInt(max - min + 1) + min;
        return randomNum;
    }

通过计算获得百分比。

    /**
     * 通过计算获得百分比。
     * @param x
     * @param y
     * @return
     */
    private String generaPercent(Integer x,Integer y){
        DecimalFormat decimalFormat = new DecimalFormat("0%");
        //设置精确几位小数。
        decimalFormat.setMaximumFractionDigits(2);
        //模式,例如四舍五入。
        decimalFormat.setRoundingMode(RoundingMode.HALF_UP);
        double accuracy_num = x * 1.0/ y * 1.0;
        return decimalFormat.format(accuracy_num);
    }

判断对象中属性(非基础数据类型)是否存在空值。

    /**
     * 判断对象中属性(非基础数据类型)是否存在空值。
     * @param object 被判断对象。
     * @return ture所有属性均为null,false非所有属性均为null。
     */
    public static boolean isFieldNull(Object object) {
        try {
            for(Field field : object.getClass().getDeclaredFields()){
                field.setAccessible(true);
                if(StringUtils.isEmpty(field.get(object))){
                    return false;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("获取对象属性值失败: {}", e.getMessage());
            return false;
        }
        return true;
    }

判断对象是否所有属性(非基础数据类型)均为空。

    /**
     * 判断对象是否所有属性(非基础数据类型)均为空。
     * @param object 被判断对象。
     * @return ture所有属性均为null,false非所有属性均为null。
     */
    public static boolean isAllFieldNull(Object object) {
        if (Objects.isNull(object)){
            return true;
        }
        boolean flag = true;
        Class clazz = object.getClass();
        Field[] fields = clazz.getDeclaredFields();
        //循环判断属性是否为空。
        for (Field field : fields) {
            //设置属性可以访问(包含私有)。
            field.setAccessible(true);
            Object value = null;
            try {
                value = field.get(object);
                //若存在属性不为空,则非所有属性为空。
                if (value != null) {
                    flag = false;
                    break;
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return flag;
    }

获取指定目录的所有文件名。

    /**
     * 获取指定目录的所有文件名。
     * @param path 目录地址。
     */
    public static void getFile(String path){
        //获取路径所在的文件。
        File file = new File(path);
        //获取文件中文件列表。
        File[] array = file.listFiles();
        for(int i = 0;i < array.length;i++){
            if(array[i].isFile()){
                //获取文件名。
                System.out.println("文件名称:" + array[i].getName());
                //获取文件路径。
                System.out.println("文件路径:" + array[i].getPath());
            }else if(array[i].isDirectory()){
                getFile(array[i].getPath());
            }
        }
    }

根据路径及文件名称删除指定文件。

    /**
     * 根据路径及文件名称删除指定文件。
     * @param path 文件夹路径。
     * @param fileName 完整的文件名。
     */
    public static void deleteFile(String path,String fileName){
        //获取路径所在的文件。
        File folder = new File(path);
        //获取文件中文件列表。
        File[] files = folder.listFiles();
        //循环匹配文件名和目标文件名。
        for(File file:files){
            if(file.getName().equals(fileName)){
                file.delete();
            }
        }
    }
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值