所以要实现我之前关于处理原始列表而不是先创建巨大字符串的评论。
static final Pattern PATTERN = Pattern.compile("(.*http)(.*)");
public static <T> String toHugeStringReplacingCommas(List<T> list, Function<T, String> convertToString) {
// we're collecting a lot of Strings, a StringBuilder is most efficient
StringBuilder builder = new StringBuilder();
for (T item : list) {
String string = convertToString(item);
Matcher m = PATTERN.matcher(string);
if (m.isMatch(string)) {
// everything up to and including "http"
StringBuilder replaced = new StringBuilder(m.groups(1));
replaced.append(m.groups(2).replaceAll(",", "\n"));
string = replaced.toString();
}
builder.append(string);
}
return builder.toString();
}
这将在您构建“巨大的字符串”时进行替换,因此它应该更有效率。但是,它确实要求每个项目中都存在“http”才能替换其余项目;如果它总体上只发生一次,您需要跟踪它是否在更早的时间发生,如下所示:
public static <T> String toHugeStringReplacingCommas(List<T> list, Function<T, String> convertToString) {
StringBuilder builder = new StringBuilder();
boolean httpFound = false;
for (T item : list) {
String string = convertToString(item);
if (!httpFound) {
Matcher m = PATTERN.matcher(string);
httpFound = m.isMatch(string);
if (httpFound) {
// we found the first occurance of "http"
// append the part up to http without replacing,
// leave the replacing of the rest to be done outside the loop
builder.append(m.groups(1));
string = m.groups(2);
}
}
if (httpFound) {
string = string.replaceAll(",", "\n");
}
builder.append(string);
}
return builder.toString();
}
如果您正在构建的 List 包含以字符串开头的字符串,则可以将 T 和 convertToString 的东西放在一边,然后做
public static String toHugeStringReplacingCommas(List<String> list) {
StringBuilder builder = new StringBuilder();
for (String string : list) {
// and so on