开发者社区> 问答> 正文

如果第二个列表中的一项满足条件,则Java 8 foreach将添加到新列表中并返回新列表

我想知道是否可以使这种方法更好,所以我有这种方法:

public int getLabelIdByLabelName(String labelName) throws ApiException {
    List<LabelInfo> labelsList = getAllLabels();
    return labelsList.stream()
            .filter(label -> label.getName().equals(labelName))
            .findFirst()
            .map(LabelInfo::getId)
            .orElse(0);
}

这是使用它的方法:

public void enableSpecificDevices(RuleIdentifier identifier, String[] labelNames) throws ApiException {
    List<Integer> labelsIdList = getLabelListById(identifier);

    for (String labelName : labelNames) {
        labelsIdList.remove(Integer.valueOf(deviceAPI.getLabelIdByLabelName(labelName)));
    }

    DisableRequest disableRequest = getDisableRequestBody(deviceIdList, labelsIdList);
    sendDisableEnableRequest(disableRequest, identifier);
}

此方法返回int值:deviceAPI.getLabelIdByLabelName(labelName)。

正如您在for循环中看到的那样,我getLabelIdByLabelName每次都在调用然后执行我需要的逻辑,它无缘无故地消耗资源,我想知道如何从该列表返回整数列表,这将是这样的:循环一次获取List在与名称相同的名称数组上,并将其添加到新的整数列表中并返回。

问题来源:Stack Overflow

展开
收起
montos 2020-03-22 15:49:37 731 0
1 条回答
写回答
取消 提交回答
  • 如果将labelName和收集id到Map,然后Map在服务方法中使用它,则可以简化它,例如:

    public Map<String, Integer> labelIdByNameMap() throws ApiException {
        List<LabelInfo> labelsList = getAllLabels();
        Map<String, Integer> labelNameToIdMap = labelsList.stream()
                .collect(Collectors.toMap(LabelInfo::getName, LabelInfo::getId));
        return labelNameToIdMap;
    }
    

    进一步将其用作:

    public void enableSpecificDevices(RuleIdentifier identifier, String[] labelNames) throws ApiException {
        Set<String> labelNameSet = Arrays.stream(labelNames).collect(Collectors.toSet());
        List<Integer> filteredValuesToRemove = labelIdByNameMap().entrySet().stream()
                .filter(e -> labelNameSet.contains(e.getKey()))
                .map(Map.Entry::getValue)
                .collect(Collectors.toList());
    
        List<Integer> labelsIdList = getLabelListById(identifier);
        labelsIdList.removeAll(filteredValuesToRemove);
    
        DisableRequest disableRequest = getDisableRequestBody(deviceIdList, labelsIdList);
        sendDisableEnableRequest(disableRequest, identifier);
    }
    

    附带说明,在现实生活中,查询所有标签可能最终会花费一些时间,其中应该在处理内存中的所有项目与执行批读取与基于进行单个数据库查找之间进行权衡,name以得到id预期的结果。

    回答来源:Stack Overflow

    2020-03-22 15:50:35
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
Spring Cloud Alibaba - 重新定义 Java Cloud-Native 立即下载
The Reactive Cloud Native Arch 立即下载
JAVA开发手册1.5.0 立即下载