Java 8如何使用Lambda表达式简化for循环

huangapple go评论47阅读模式
英文:

Java 8 how to simplify for loop with lambda expressions

问题

我有这个方法在我的代码中,需要使用Java 8表达式来简化和减少代码行数。Lambda可以用于这个,但似乎没有一个列表作为输入是不可能的。

我尝试过使用resourceUsages.forEach(resourceUsages.resource-> do something);,但没有列表作为输入似乎是不可能的。

有没有简化这段代码的方法?

英文:

I have this method in my code and need o simplify and reduce lines by using java 8 expressions.
Lambda can be used for this but it seems impossible without a list as input.

  public ResourceUsage[] filterResourceUsages(ResourceUsage[] resourceUsages, int role, int includeResourceType)
    throws SpiderException
  {
    ArrayList<ResourceUsage> filteredResourceUsages = new ArrayList<>();

    String[] ids = new String[resourceUsages.length];
    for (int i = 0; i < resourceUsages.length; i++)
    {
      ids[i] = resourceUsages[i].resource;
    }

    ResourceData[] resourceData = resourceToolkitAdapter.getData(ids);

    for (int i = 0; i < resourceData.length; i++)
    {
      if (resourceUsages[i].role == role && resourceData[i].basic.type == includeResourceType)
      {
        filteredResourceUsages.add(resourceUsages[i]);
      }
    }
    return filteredResourceUsages.toArray(new ResourceUsage[filteredResourceUsages.size()]);
  }

I have tried using resourceUsages.forEach(resourceUsages.resource-> do something); but without list as input it seems impossible.

Is there any way to simplify this code?

答案1

得分: 7

以下是原始的代码片段及其翻译部分:

// 这是原始的数组和批处理解决方案:
public ResourceUsage[] filterResourceUsages(ResourceUsage[] resourceUsages, int role, int includeResourceType)
        throws SpiderException {

    // 将资源使用对象中的资源名称提取到一个字符串数组中
    String[] ids = Stream.of(resourceUsages)
            .map(ResourceUsage::getResource)
            .toArray(String[]::new);

    // 使用资源工具适配器获取资源数据,并将其映射到资源ID上
    Map<String, ResourceData> resourceDataMap = Stream.of(resourceToolkitAdapter.getData(ids))
            .collect(Collectors.toMap(ResourceData::id, Function.identity()));

    // 过滤资源使用对象的数组,根据角色和包括的资源类型
    return Stream.of(resourceUsages)
            .filter(usage -> usage.role == usage) // 这里可能需要修正,根据实际逻辑
            .filter(resourceDataMap::containsKey)
            .filter(usage -> resourceDataMap.get(usage.resource).basic.type == includeResourceType)
            .toArray(ResourceUsage[]::new);
}

希望这个翻译对您有所帮助。

英文:

here is the origin arrays and batch solution:

public ResourceUsage[] filterResourceUsages(ResourceUsage[] resourceUsages, int role, int includeResourceType)
        throws SpiderException {

    String[] ids = Stream.of(resourceUsages)
            .map(ResourceUsage::getResource)
            .toArray(String[]::new);
    Map&lt;String, ResourceData&gt; resourceDataMap = Stream.of(resourceToolkitAdapter.getData(ids))
            .collect(Collectors.toMap(ResourceData::id, Function.identity()));
    return Stream.of(resourceUsages)
            .filter(usage -&gt; usage.role == usage)
            .filter(resourceDataMap::containsKey)
            .filter(usage -&gt; resourceDataMap.get(usage.resource).basic.type == includeResourceType)
            .toArray(ResourceUsage[]::new);
}

答案2

得分: 3

你可以像这样使用数组:

Arrays.stream(resourceUsages)
    .forEach(e -> System.out.print(e));
英文:

You can do like this with arrays

Arrays.stream(resourceUsages) 
            .forEach(e-&gt;System.out.print(e));

答案3

得分: 2

最好使用 List<ResourceUsage> 而不是数组。

我也会假设逐个调用 resourceToolkitAdapter.getData() 对每个资源而言是可以的,而不是批量操作。

结果将类似于以下内容:

public List<ResourceUsage> filterResourceUsages(List<ResourceUsage> resourceUsages, int role, int includeResourceType)
        throws SpiderException
{
    return resourceUsages.stream()
            .filter(r -> r.role == role)
            .filter(r -> resourceToolkitAdapter.getData(r.resource).basic.type == includeResourceType)
            .collect(Collectors.toList());
}
英文:

It's best if you use List&lt;ResourceUsage&gt; rather than arrays.

I'm also going to pretend it's ok to call resourceToolkitAdapter.getData() on each resource in turn, rather than in bulk.

The result will be something like so:

    public List&lt;ResourceUsage&gt; filterResourceUsages(List&lt;ResourceUsage&gt; resourceUsages, int role, int includeResourceType)
            throws SpiderException
    {
        return resourceUsages.stream()
                .filter(r-&gt;r.role == role)
                .filter(r-&gt;resourceToolkitAdapter.getData(r.resource).basic.type == includeResourceType)
                .collect(Collectors.toList());
    }   

答案4

得分: 2

I assume that resourceToolkitAdapter.getData() should be called with a batch of ids.

我认为应该使用一批 ID 调用 resourceToolkitAdapter.getData()

英文:

Opposed to the answer of Matthew, I assume that resourceToolkitAdapter.getData() should be called with a batch of ids.

public ResourceUsage[] filterResourceUsages(ResourceUsage[] resourceUsages, int role, int includeResourceType)
  throws SpiderException
{
  ResourceData[] resourceData = resourceToolkitAdapter.getData(
    Arrays.stream(resourceUsages)
      .map(r -&gt; r.resource)
      .toArray(String[]::new)
  );

  return IntStream
    .range(0, resourceData.length)
    .filter(i -&gt; resourceUsages[i].role == role )
    .filter(i -&gt; resourceData[i].basic.type == includeResourceType)
    .mapToObj(i -&gt; resourceUsages[i])
    .toArray(ResourceUsage[]::new);
}

huangapple
  • 本文由 发表于 2020年8月3日 19:50:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/63228907.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定