簡體   English   中英

Java:從ArrayList獲取所有第一個條目

[英]Java: Get all first entries from ArrayList

我有一個包含用戶信息數組的ArrayList(〜900個條目):

[swaschit, Sophia Waschitz, Dormant, Inactive, 1/1/2018]
[kolanday, Kyle Olanday, Dormant, Inactive, 1/1/2018]
[npowers, Neil Powers, Assigned, Active, 2/11/2018]

我想從此列表生成一個僅包含每個對象的第一個元素的數組:

[swaschit, kolanday, npowers, ...]

最有效的方法是什么?

一種方法是使用Stream並將每個內部數組map到其第一個元素:

List<String> firstElements = yourList.stream()
                                     .map(x -> x[0].toString()) // you might need toString() here if your array is an Object[]
                                     .collect(Collectors.toList());

如果您想要一個字符串數組來代替:

String[] firstElements = yourList.stream()
                                     .map(x -> x[0].toString()) // you might need toString() here if your array is an Object[]
                                     .toArray(String[]::new);

我還建議您不要使用這樣的嵌套數組。 您應該使用要存儲的屬性創建一個類,並創建一個類List

因為我認為第一個條目是唯一的(因為它似乎是用戶名),所以我建議使用Map。 這樣,您只需列出密鑰即可。

HashMap<String,ArrayList<String>> hashmap=new HashMap<>();

另外,您可以簡單地創建一個包含該信息的類,以避免需要使用ArrayList,但是我不知道這是否是一個選擇。

如前所述,使用適當設計的Object而不是此類異構數據的array (實際上,它們是String )。

如果堅持使用現有方法,則只需要分配一個具有原始ArrayList大小的新數組並進行迭代,以獲取所需的列即可。 假設ArrayList<String[]> list

int size = list.size();
String[] firstColumn = new String[size];
for (int i = 0; i < list.size(); i++) {
    firstColumn[i] = list.get(i)[0];
}

我想你可以做list.stream().map(array -> array[0].toString()).toArray()

暫無
暫無

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

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