Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 how to simplify for loop with lambda expressions

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?

like image 637
Codeninja Avatar asked Dec 03 '22 17:12

Codeninja


1 Answers

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<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);
}
like image 81
ggbond Avatar answered Dec 23 '22 07:12

ggbond