替换“ for”循环以提高性能

时间:2018-09-14 09:07:17

标签: java

我需要帮助,将URL替换为“ 868768675876867867867867867768678”到“ {data}”,但不使用for循环,因为会有超过10000个url进入,它将失去性能,因此我想替换for循环。请帮我,因为我在进行转换时遇到问题

private static Boolean moreThen10NumbersInString (ArrayList<String> arrayList) { // this method checks if the url is having more than 8 digits then it replaces it with "{data}"
    int numberOfNumbers = 0;
    String replace = "{Data}";

        for(String string : arrayList){

            for(int j=0; j < string.length(); j++){

                if (Character.isDigit(string.charAt(j))) {
                //System.out.println(string);
                numberOfNumbers++;


                if (numberOfNumbers > 8) { // 8 is used as some standard number to check its numeric content

                    int x = arrayList.indexOf(string);
                    arrayList.remove(x);
                    arrayList.add(x, replace);
                    return true;
                }

            }
            }
        }


    return false;
}

public static void main(String[] args) {

    String url = "/this/is/a/url/with/number/868768675876867867876867768678/replace/to/data"; //this url is just a mock data
    String[] split = url.split("/"); //url will be splitted by "/"
    ArrayList<String> arrayList = new ArrayList<String>();

    for(String s : split){
        //System.out.println(s);
        if(s!=null && s!=""){
            arrayList.add(s);
        }
        else{
            arrayList.remove(s);
        }
    }

    moreThen10NumbersInString(arrayList);

        if(Boolean.TRUE){ //if the url contains numbers part
            for(String str : arrayList){

                System.out.print(str+"/");

            }
        }
        if(Boolean.FALSE) //if the url doesnt contain any numbers part
        {
        System.out.println(url);    
        }

}

}

1 个答案:

答案 0 :(得分:4)

您要做的就是替换URL中的纯数字路径。为此,只需使用String.replace

以下内容使用正则表达式来匹配和替换数字路径。这是您可能需要的所有代码(仅在main中):

String url = "/this/is/a/url/with/number/868768675876867867876867768678/replace/to/data";

//finds "/<numbers>/" and replaces with /{data}/
String result = url.replaceAll("/\\d{8,}/", "/{data}/");
System.out.println(result);

显示"/this/is/a/url/with/number/{Data}/replace/to/data/"