![](/img/trans.png)
[英]how to create java generic method which returns String or ArrayList<String>
[英]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.