Problem Statement : Let's say I've list of PriceRow(productCode, key, sector)
objects
List<PriceRow> priceRowList = new ArrayList<>();
priceRowList.add(new PriceRow("10kgbag","", "SECTOR"));
priceRowList.add(new PriceRow("10kgbag","12345", ""));
priceRowList.add(new PriceRow("10kgbag","", ""));
priceRowList.add(new PriceRow("20kgbag","", "SECTOR"));
priceRowList.add(new PriceRow("20kgbag","12345", ""));
priceRowList.add(new PriceRow("20kgbag","", ""));
priceRowList.add(new PriceRow("30kgbag","", "SECTOR"));
priceRowList.add(new PriceRow("30kgbag","", ""));
priceRowList.add(new PriceRow("40kgbag","", ""));
priceRowList.add(new PriceRow("50kgbag","", ""));
Now, I need to group it by productCode, and then sort it on the basis of first key then sector, if both rows are not available then take the row with (key = blank) and (sector=blank) and now take the first row out of the sorted list to create a Map<String, PriceRow)
Hence the final assertions should look like
assertEquals("12345",map.get("10kgbag").getFlightKey());
assertEquals("12345",map.get("20kgbag").getFlightKey());
assertEquals("SECTOR",map.get("30kgbag").getSector());
assertEquals("",map.get("40kgbag").getFlightKey());
assertEquals("",map.get("50kgbag").getFlightKey());
The solution I came up with is
import org.apache.commons.lang.StringUtils;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class Example {
public Map<String,PriceRow> evaluate(List<PriceRow> priceRowList) {
Map<String,PriceRow> map = priceRowList.stream()
.collect(Collectors.groupingBy(priceRow -> priceRow.getProductCode(),
Collectors.collectingAndThen(Collectors.toList(), value -> getMostEligibleValue(value))));
return map;
}
private PriceRow getMostEligibleValue(List<PriceRow> priceRowList){
for(PriceRow priceRowWithKey : priceRowList)
if(StringUtils.isNotBlank(priceRowWithKey.getKey()))
return priceRowWithKey;
for(PriceRow priceRowWithSector : priceRowList)
if(StringUtils.isNotBlank(priceRowWithSector.getSector()))
return priceRowWithSector;
return priceRowList.stream().findFirst().get();
}
}
Hope I'm able to explain the problem statement. If there are any better solutions for this problem, pls let me know. Thanks in advance for your help.