gpt4 book ai didi

java - 在添加到集合之前过滤对象的最简洁方法?

转载 作者:行者123 更新时间:2023-12-02 09:10:30 25 4
gpt4 key购买 nike

  private List<BusinessObject> createList(int property1, List<String> filenames) {
List<BusinessObject> objectList = new ArrayList();
filenames.forEach(filename -> {
BusinessObject businessObj = parseObject(filename);
if (businessObj.getProperty1() == property1) {
objectList.add(businessObj);
}
});
return objectList;
}

我觉得一定有一个更惯用的或类似于 Java 8 的解决方案,例如

filesnames.forEach(fileName -> parseObject(fileName)).(some method that takes the output of parseObject)

最佳答案

确切的流等效项是:

return filenames.stream()
.map(filename -> parseObject(filename))
.filter(o -> o.getProperty1() == property1)
.collect(Collectors.toCollection(ArrayList::new));

关于java - 在添加到集合之前过滤对象的最简洁方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59459479/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com