Skip to content

Instantly share code, notes, and snippets.

@mcalavera81
Created October 28, 2015 20:40
Show Gist options
  • Save mcalavera81/c848be61749bf36337bf to your computer and use it in GitHub Desktop.
Save mcalavera81/c848be61749bf36337bf to your computer and use it in GitHub Desktop.
Strategy Pattern with Lambda expressions.
package com.example;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
public class MessingAround {
public static int totalAssetValues(final List<Asset> assets,
final Predicate<Asset> assetSelector) {
return assets.stream().filter(assetSelector).mapToInt(Asset::getValue).sum();
}
public static void main(String[] args) throws IOException, InterruptedException {
final List<Asset> assets = Arrays.asList(
new Asset(Asset.AssetType.BOND, 1000),
new Asset(Asset.AssetType.BOND, 2000),
new Asset(Asset.AssetType.STOCK, 3000),
new Asset(Asset.AssetType.STOCK, 4000)
);
System.out.println("Total of all assets: " + totalAssetValues(assets, asset -> true));
System.out.println("Total of bonds: " +
totalAssetValues(assets, asset -> asset.getType() == Asset.AssetType.BOND));
System.out.println("Total of stocks: " +
totalAssetValues(assets, asset -> asset.getType() == Asset.AssetType.STOCK));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment