簡體   English   中英

將Java字符串數組合並到一個對象中

[英]Combine Java string arrays into one object

嗨,我想要以編程方式組合這三個靜態對象。 例如:

private static final String[] DESEASE = new String[] {
    "Alcoholism", "Animal Desease", "Brain Desease", "Demantia", "Movement Disorder"
};

private static final String[] GENE = new String[] {
    "A1CF", "A2LD1", "A2M", "AA06", "AA1"
};

private static final String[] GEO = new String[] {
    "GSE14429", "GSE4226", "GSE8632", "GS9134", "GSE8641"
};

我不想迭代。 想要做一些類型的事情:

String[] resultList = DESEASE resultList.addAll(GENE).addAll(GEO);

我認為沒有一種非常簡潔的方法可以做到這一點。 這將工作,而不使用第三方庫,但不完全漂亮:

private static final String[] resultList;
static {
    List<String> tmpList = new ArrayList<String>(Arrays.asList(DESEASE));
    tmpList.addAll(Arrays.asList(GENE));
    tmpList.addAll(Arrays.asList(GEO));
    resultList = tmpList.toArray(new String[tmpList.size()]);
}

您可以嘗試使用Collection ,它提供了您給出的示例的幾乎文字版本:

List<String> data = new ArrayList<String>();
data.addAll(Arrays.asList(DESEASE));
data.addAll(Arrays.asList(GENE));
data.addAll(Arrays.asList(GEO));
String[] resultList = data.toArray(new String[data.size()]);

這基本上創建了一個新的Collection,並在將其轉換回數組之前添加了所有內容。

或者您可以使用新數組和System.arraycopy方法執行此操作:

String[] resultList = new String[DESEASE.length + GENE.length + GEO.length];
System.arraycopy(DESEASE, 0, resultList, 0, DESEASE.length);
System.arraycopy(GENE, 0, resultList, DESEASE.length, GENE.length);
System.arraycopy(GEO, 0, resultList, DESEASE.length + GENE.length, GEO.length);

這將創建一個新陣列並將每個子陣列復制到所需的插槽中。

我實際上沒有測試哪個更快但System.arraycopy輸出到本機方法並沒有那么多的對象創建所以我會打賭那個。

這是兩個解決方案(Collections和System.arraycopy() ):

類別:

    List<String> allAsList = new ArrayList<>();
    allAsList.addAll(Arrays.asList(DESEASE));
    allAsList.addAll(Arrays.asList(GENE));
    allAsList.addAll(Arrays.asList(GEO));
    System.out.println(allAsList);

ArrayCopy:

    String[] allAsArray = new String[DESEASE.length + GENE.length + GEO.length];
    System.arraycopy(DESEASE, 0, allAsArray, 0, DESEASE.length);
    System.arraycopy(GENE, 0, allAsArray, DESEASE.length, GENE.length);
    System.arraycopy(GEO, 0, allAsArray, DESEASE.length + GENE.length, GEO.length);
    System.out.println(Arrays.asList(allAsArray));

您可以使用Google Guava中的ObjectArrays.concat(T[],T[],Class<T>) ,然后使用嵌套調用:

import static com.google.common.collect.ObjectArrays.concat;
...
final String [] resultList = concat(DESEASE, concat(GENE, GEO, String.class), String.class);

但是,列表更靈活。

怎么樣這樣:

public String[] combineArray (String[] ... strings) {
    List<String> tmpList = new ArrayList<String>();
    for (int i = 0; i < strings.length; i++)
        tmpList.addAll(Arrays.asList(strings[i]));
    return tmpList.toArray(new String[tmpList.size()]);
}

你可以傳遞盡可能多的參數:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM