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?
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With