Skip to content
Advertisement

Extracting multiple string to constant in Intellij IDEA

In my code, there are a lot of strings appeared in the following structure:

map.put("string_1", value_1);
map.put("string_2", value_2);
// etc.

I would like to extract the string key to a constant. However, doing this one by one will take forever…So, is there a better way to achieve this?

Advertisement

Answer

No idea in Intellij, but if your lines are genuinely that simple, you can do it with a bit of command line fu:

grep map.put YourClass.java | awk -F" '{print "public static final String " $2 " = "" $2 "";"}'

to get the string declarations:

public static final String string_1 = "string_1";
public static final String string_2 = "string_2";

Then

grep map.put YourClass.java | awk -F" '{print $1 $2 $3}'

to replace the map.put lines.

map.put(string_1, value_1);
map.put(string_2, value_2);

Copy and paste from the command line into your file; or use a text editor which lets you do it inline (e.g. in Vim, shift+V to select the lines, then :! and enter the awk command from above).

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement