Pradheep Soma
Pradheep Soma

Reputation: 1

Replace "for" loop to improve performance

I need help to replace the url with "868768675876867867876867768678" to "{data}" but without using for loop as there will be more than 10000 url coming in, it will lose performance and so i would like to replace the for loops. Please help me in this as i'm facing issues while doing this transformation

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);    
        }

}

}

Upvotes: 0

Views: 241

Answers (1)

ernest_k
ernest_k

Reputation: 45309

All you're trying to do is replace a digit-only path from the URL. For that, just use String.replace.

The following uses a regular expression to match and replace the numeric path. And here's all the code you may need (in main only):

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);

That prints "/this/is/a/url/with/number/{Data}/replace/to/data/"

Upvotes: 4

Related Questions