Skip to content

Instantly share code, notes, and snippets.

@maxant
Last active August 29, 2015 14:12
Show Gist options
  • Save maxant/9819dff79ae7dc723e3d to your computer and use it in GitHub Desktop.
Save maxant/9819dff79ae7dc723e3d to your computer and use it in GitHub Desktop.
Trading method of Java market
public List<Sale> trade() {
List<Sale> sales = new ArrayList<>();
Set<String> productsInMarket = getProductsInMarket();
collectMarketInfo();
// trade each product in succession
productsInMarket.stream()
.forEach(productId -> {
MutableBoolean soldOutOfProduct = new MutableBoolean(false);
LOGGER.debug("trading product " + productId);
List<Buyer> buyersInterestedInProduct = getBuyersInterestedInProduct(productId);
if (buyersInterestedInProduct.size() == 0) {
LOGGER.info("no buyers interested in product " + productId);
} else {
buyersInterestedInProduct.forEach(buyer -> {
if (soldOutOfProduct.isFalse()) {
LOGGER.debug(" buyer " + buyer.getName() + " is searching for product " + productId);
// select the cheapest seller
Optional<Seller> cheapestSeller = sellers.stream()
.filter(seller -> { return seller.hasProduct(productId);})
.sorted((s1, s2) ->
Double.compare(s1.getCheapestSalesOrder(productId).getPrice(),
s2.getCheapestSalesOrder(productId).getPrice()))
.findFirst();
if (cheapestSeller.isPresent()) {
LOGGER.debug(" cheapest seller is " + cheapestSeller.get().getName());
List<Sale> newSales = createSale(buyer, cheapestSeller.get(), productId);
sales.addAll(newSales);
LOGGER.debug(" sales completed");
} else {
LOGGER.warn(" market sold out of product " + productId);
soldOutOfProduct.setTrue();
}
}
});
}
});
return sales;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment