Skip to content

Commit

Permalink
add StringUtils#deepReplace
Browse files Browse the repository at this point in the history
  • Loading branch information
HSGamer committed Mar 16, 2024
1 parent 321aeb9 commit 237a487
Showing 1 changed file with 25 additions and 1 deletion.
26 changes: 25 additions & 1 deletion common/src/main/java/me/hsgamer/hscore/common/StringUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.Map;
import java.util.*;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.function.UnaryOperator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

Expand Down Expand Up @@ -191,4 +192,27 @@ public static char[] normalizeHex(@NotNull final String input) {
}
return chars;
}

/**
* Replace the string in the object
*
* @param object the object
* @param replacer the replacer
*
* @return the replaced object
*/
public static Object deepReplace(Object object, UnaryOperator<String> replacer) {
if (object instanceof String) {
return replacer.apply((String) object);
} else if (object instanceof Collection) {
List<Object> replaceList = new ArrayList<>();
((Collection<?>) object).forEach(o -> replaceList.add(deepReplace(o, replacer)));
return replaceList;
} else if (object instanceof Map) {
Map<Object, Object> replaceMap = new LinkedHashMap<>();
((Map<?, ?>) object).forEach((k, v) -> replaceMap.put(k, deepReplace(v, replacer)));
return replaceMap;
}
return object;
}
}

0 comments on commit 237a487

Please sign in to comment.