3

I want to replace three Strings that are present in multiple files. Say I want to replace "EVENT" with "MYEVENT", "TRACE" with "TRACE" and "LOGS" with "MYLOGS". I have written three functions for it but I want to combine these functions into a single function.

One of my functions is:

public static void findAndReplaceKey(String filePath) {

    try {
        Path path = Paths.get(filePath);
        Stream<String> lines = Files.lines(path);
        List<String> replaced = lines.map(line -> line.replaceAll("TRACE", "MYTRACE")).collect(Collectors.toList());
        Files.write(path, replaced);
        lines.close();
        // System.out.println("Find and Replace done!!!");
    } catch (IOException e) {
        e.printStackTrace();
    }

}

These three functions collectively takes around 7 seconds so I want to reduce the time by combining them into a single function.

Can you please also help me if i have "N" number of replacements to be made. Say replace ABC with 123, DEF with 234, GEF with 4567, LMN with 8910 and so on...... I am getting these values from key-value pair of properties file

2 Answers 2

6

How about:

List<String> replaced = 
    lines.map(line -> line.replace("TRACE", "MYTRACE").replace("LOGS","MYLOGS").replace("EVENT","MYEVENT"))
         .collect(Collectors.toList());
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks it worked and now the task is achievable in around 2 seconds
Can you please also help me if i have "N" number of replacements to be made. Say replace ABC with 123, DEF with 234, GEF with 4567, LMN with 8910 and so on...... I am getting these values from key-value pair of properties file.
3

Using a regex will probably be more readable and future proof

List<String> replaced = lines.map(line -> line.replaceAll("(TRACE|LOGS|EVENT)", "MY$1")
                             .collect(Collectors.toList());

1 Comment

Can you please also help me if i have "N" number of replacements to be made. Say replace ABC with 123, DEF with 234, GEF with 4567, LMN with 8910 and so on...... I am getting these values from key-value pair of properties file

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.