Java 从返回字符串的方法创建ArrayList
我有一个自定义类Java 从返回字符串的方法创建ArrayList,java,Java,我有一个自定义类InfoAQ,它有一个名为publicstringgetseqinf()的方法。现在我有了一个arraylistinflist和 I需要一个arraylistrlist=new ArrayList,每个元素的内容都来自getSeqInf() 这就是我现在做这件事的方式 for(InfoAQ currentInf : infList) strList.add(currentInf.getSeqInf()); 有没有别的办法?也许是更快的一艘或一艘班轮?是的,有: strLis
InfoAQ
,它有一个名为publicstringgetseqinf()
的方法。现在我有了一个arraylistinflist
和
I需要一个arraylistrlist=new ArrayList
,每个元素的内容都来自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
,它将像在您的案例中一样保存结果。(如果您确实关心结果列表类型为Collectors,这一点很重要。toList()
不保证这一点)
可能不是最快的,因为使用流有一些开销。您需要测量/基准以了解其性能也可能是以下性能:
List<String> strList = new ArrayList<String>();
infList.forEach(e -> strList.add(e.getSeqInf()));
List strList=new ArrayList();
forEach(e->strList.add(e.getSeqInf());
还有另一个(-liner,如果您将其格式化为单行):
虽然我更喜欢更多行的格式:
infList.forEach(currentInf -> {
strList.add(currentInf.getSeqInf());
});
此代码将迭代列表中的所有数据,当getSeqInf返回字符串时,collect方法将getSeqInf方法的所有返回存储在列表中。
`List listString=infList.stream().map(InfoAQ::getSeqInf).collect(Collectors.toList())`
或
`
ArrayList listString=新的ArrayList();
对于(int i=0;i
Try this-->List outputList=List.stream().map(it->it.getSeqInf()).collect(Collectors.toList())的可能重复项;你写的可以是一行。只需删除您添加的新行。InfoAQ::getSeqInf?这是map的等效方法。好建议。
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());
}`