Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace multiple strings using a single function in java 8

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

like image 607
Anurag Sharma Avatar asked Nov 26 '25 13:11

Anurag Sharma


1 Answers

How about:

List<String> replaced = 
    lines.map(line -> line.replace("TRACE", "MYTRACE").replace("LOGS","MYLOGS").replace("EVENT","MYEVENT"))
         .collect(Collectors.toList());
like image 90
Eran Avatar answered Nov 28 '25 03:11

Eran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!