如何在列表中每个元素的末尾附加“ _INC”(字符串)?

时间:2018-12-03 21:56:32

标签: java arrays

我想将“ _INC”附加到列表中的每个元素。列表内容如下:

public final static List<String> PROVIDERS = Arrays.asList("asco_genes", "pubmed_oa_genes", "wiley_journals_genes", "mms_genes", "elsevier_genes", "medline_genes",
            "asco_drugs", "pubmed_oa_drugs", "wiley_journals_drugs", "mms_drugs", "elsevier_drugs", "medline_drugs", "aaas_genes", "aaas_drugs", "aacr_genes","aacr_drugs",
            "springer_nature_genes", "springer_nature_drugs");

在编程逻辑之后,列表应如下所示:

 public final static List<String> PROVIDERS = Arrays.asList("asco_genes_INC", "pubmed_oa_genes_INC", "wiley_journals_genes_INC", "mms_genes_INC", "elsevier_genes_INC", "medline_genes_INC",
                "asco_drugs_INC", "pubmed_oa_drugs_INC", "wiley_journals_drugs_INC", "mms_drugs_INC", "elsevier_drugs_INC", "medline_drugs_INC", "aaas_genes_INC", "aaas_drugs_INC", "aacr_genes_INC","aacr_drugs_INC",
                "springer_nature_genes_INC", "springer_nature_drugs_INC");

我研究过使用字符串生成器和使用字符数组来完成任务,但是它们看起来有点复杂。我想知道java是否有任何预定义的库可以使此操作更容易。

3 个答案:

答案 0 :(得分:6)

Java 8+,您可以创建stream并添加"_INC",然后将其收集到List中:

List<String> list = Stream.of("asco_genes", "pubmed_oa_genes", "wiley_journals_genes", "mms_genes", "elsevier_genes", "medline_genes",
        "asco_drugs", "pubmed_oa_drugs", "wiley_journals_drugs", "mms_drugs", "elsevier_drugs", "medline_drugs", "aaas_genes", "aaas_drugs", "aacr_genes","aacr_drugs",
        "springer_nature_genes", "springer_nature_drugs")
                          .map(e -> e + "_INC")
                          .collect(Collectors.toList());

哪个会产生:

mms_genes_INC
elsevier_genes_INC
medline_genes_INC
asco_drugs_INC
pubmed_oa_drugs_INC
wiley_journals_drugs_INC
mms_drugs_INC
elsevier_drugs_INC
medline_drugs_INC
aaas_genes_INC
aaas_drugs_INC
aacr_genes_INC
aacr_drugs_INC
springer_nature_genes_INC
springer_nature_drugs_INC

答案 1 :(得分:3)

您实际上不需要流也不需要for循环(前提是您使用Java 8或更高版本;请使用问题中的声明):

    PROVIDERS.replaceAll(s -> s + "_INC");

结果:

asco_genes_INC
pubmed_oa_genes_INC
wiley_journals_genes_INC
mms_genes_INC
elsevier_genes_INC
medline_genes_INC
asco_drugs_INC
pubmed_oa_drugs_INC
wiley_journals_drugs_INC
mms_drugs_INC
elsevier_drugs_INC
medline_drugs_INC
aaas_genes_INC
aaas_drugs_INC
aacr_genes_INC
aacr_drugs_INC
springer_nature_genes_INC
springer_nature_drugs_INC

答案 2 :(得分:2)

出于完整性考虑,如果您无权访问lambda,并且如果该列表可变,并且您不想创建新列表,请替换列表中的所有元素与新的String对象:

List<String> lst = Arrays.asList(...);
int n = lst.size();
for (int i = 0; i < n; i++) { // Or lst.size() if you fear concurrent accesses
    lst.set(i, lst.get(i)+"_INC"); // Or lst.get(i).concat("_INC")
}

两个注意事项:

  • String是不可变的,因此您无法更改其内容
  • 如果List实现具有随机访问权限(例如ArrayList),则不会产生运行时损失,但是对于非随机访问实现(例如LinkedList),它的运行效果欠佳。 / li>