簡體   English   中英

從返回字符串的方法創建ArrayList

[英]Creating an ArrayList from a method which returns a String

我有一個自定義類InfoAQ ,它具有一個稱為public String getSeqInf() 現在我有了一個ArrayList<InfoAQ> infList ,我需要一個ArrayList<String>strList = new ArrayList<String> ,其中包含每個元素的getSeqInf()中的內容。

我現在就是這樣做的方式...

for(InfoAQ currentInf : infList)
  strList.add(currentInf.getSeqInf());

有其他替代方法嗎? 也許更快的一個或一個班輪?

就在這里:

strList = infList.stream().map(e -> g.getSeqInf()).collect(Collectors.toList());

map步驟也可以用另一種方式編寫:

strList = infList.stream().map(InfoAQ::getSeqInf).collect(Collectors.toList());

這就是方法引用傳遞。 這兩個解決方案是等效的。

使用流

infList.stream()
   .map(InfoAQ::getSeqInf)
   .collect(Collectors.toCollection(ArrayList::new))

在此處使用Collectors.toCollection創建一個ArrayList ,該ArrayList將保存您的案例中的結果。 (重要,如果在乎結果列表類型Collectors.toList()不能保證這並不)

可能不是最快的,因為使用流有一些開銷。 您需要進行度量/基准測試以了解其性能

也可能是這個:

List<String> strList = new ArrayList<String>();
infList.forEach(e -> strList.add(e.getSeqInf()));

還有另一種(襯里,如果您將其格式化為一行):

infList.forEach(currentInf -> {strList.add(currentInf.getSeqInf());});

而我希望使用更多行的格式:

infList.forEach(currentInf -> {
    strList.add(currentInf.getSeqInf());
});
This code will iterate all the data in the list, as getSeqInf returns a String, the collect method will store all returns of the getSeqInf method in a list.


`List listString = infList.stream().map(InfoAQ::getSeqInf).collect(Collectors.toList());`

or 

`
ArrayList<String> listString = new ArrayList<>();
for(int i = 0; i < infoAq.size(); i++) {
     listString.add(infoAq.get(i).getSeqInf());
}`

暫無
暫無

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

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