猿问

如何根据Java中的多个参数过滤列表中的数据?

我有一个GroupOffices列表


List<GroupOffice> officesOfTheGroup;

我想搜索 id 是否不等于groupOffice.getId (Long value) 但标签是groupOffice.getLabel (String) 并将其分配给布尔值。下面的代码运行良好,但是有没有更好的方法而不是使用 for 循环遍历所有项目?


 public GroupOfficeDto saveGroupOffice(GroupOfficeDto groupOfficeDto) {     

            List<GroupOffice> officesOfTheGroup = //some list from db..

            for (GroupOffice go : officesOfTheGroup) {

                if ((!go.getId().equals(groupOfficeDto.getId())) && go.getLabel().equals(groupOfficeDto.getLabel())) {

                    return groupOfficeDto;

                }

        return null:

}

或者我该如何使用流?如果是这样,使用流是更好的方法吗?


注意:我使用的是 Java8


Smart猫小萌
浏览 176回答 3
3回答

呼如林

有没有更好的方法而不是通过for循环遍历所有项目?值得注意的是,如果在到达列表末尾之前找到可接受的项目,您的代码不会遍历所有项目。但是,如果您只有要使用的列表,那么除了准备检查每个列表元素之外别无选择。至于是否使用for循环,我认为这很好。或者我该如何使用流?如果是这样,使用流是更好的方法吗?这些天使用流确实很流行,虽然它们的使用似乎比我认为的要多,但你的用例并不是不合理的。你可以这样写:public GroupOfficeDto saveGroupOffice(GroupOfficeDto groupOfficeDto) {&nbsp; &nbsp; &nbsp;&nbsp; &nbsp; List<GroupOffice> officesOfTheGroup = //some list from db..&nbsp; &nbsp; Integer officeId = groupOfficeDto.getId();&nbsp; &nbsp; String officeLabel = groupOfficeDto.getLabel();&nbsp; &nbsp; return officesOfTheGroup.stream()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .filter(o -> !o.getId().equals(officeId))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .anyMatch(o -> o.getLabel().equals(officeLabel))&nbsp; &nbsp; &nbsp; &nbsp; ? groupOfficeDto : null;}这里特别相关的是.anyMatch()终端操作的使用,因为它允许流处理在结果确定后立即完成,就像你的for循环一样,而不是处理整个流。另请注意,您正在比较办公室的 ID 和标签被提取并存储在流表达式之前的变量中。这允许它们“有效地最终”,这是它们出现在流中的 lambda 中所必需的。这样做也稍微更有效率,而不是一遍又一遍地从 DTO 检索相同的对象——对于for循环情况也是如此。请注意,流版本并不比循环版本简单得多,也不容易阅读。我个人认为其中任何一个都没有太多优势。

慕莱坞森

尝试这个:public GroupOfficeDto saveGroupOffice(GroupOfficeDto groupOfficeDto) {&nbsp; &nbsp; ...&nbsp; &nbsp; &nbsp;&nbsp; &nbsp; List<GroupOffice> result = officesOfTheGroup.stream()&nbsp; &nbsp; &nbsp; &nbsp; .filter(it -> it.getLabel().equals(groupOfficeDto.getLabel()))&nbsp; &nbsp; &nbsp; &nbsp; .filter(it -> !it.getId().equals(groupOfficeDto.getId()))&nbsp; &nbsp; &nbsp; &nbsp; .collect(Collectors.toList())&nbsp; &nbsp; ...}

Helenr

如果您需要布尔值,您可以执行以下操作:boolean&nbsp;b&nbsp;=&nbsp;officesOfTheGroup.stream() &nbsp;&nbsp;&nbsp;&nbsp;.anyMatch(office&nbsp;->&nbsp;!office.getId().equals(5)&nbsp;&&&nbsp;office.getLabel().equals("London"))
随时随地看视频慕课网APP

相关分类

Java
我要回答