javafunctionpredicateconsumerfunctional-interface

using functional interfaces in java


I have ProductSettings and ProductType. Product settings determine whether product types are enabled or not.

ProductSettings productSettings = new ProductSettings()
            .setIsTreasuryInfoEnabled(true)
            .setIsTreasurySwiftInfoEnabled(true)
            .setIsTreasuryExecutionControlEnabled(true)
            .setIsAcceptEnabled(true);

public enum ProductType {
INFO,
INFOSWIFT,
BUDGETCONTROL,
ACCEPT,
DIRECTACCOUNTCONTROL

how can i fill the enabledProductTypes set using functional interfaces and vs task - enable settings by having product types?

Set<ProductType> enabledProductTypes = EnumSet.noneOf(ProductType.class);

I created map

static Map<ProductType, Predicate<ProductSettings>> mapGetter = new HashMap<>();

static Map<ProductType, BiConsumer<ProductSettings, Boolean>> mapSetter = new HashMap<>();

and filled out mapGetter with Predicate like this:

mapGetter.put(ProductType.ACCEPT, ProductSettings::getIsAcceptEnabled);


mapGetter.put(ProductType.INFO,ProductSettings::getIsTreasuryInfoEnabled);

and filled out mapSetter with BiConsumer like this:

mapSetter.put(ProductType.ACCEPT, ProductSettings::setIsAcceptEnabled);

mapSetter.put(ProductType.INFO, ProductSettings::setIsTreasuryInfoEnabled);

but how to use it I can't understand. I guess i shoul iterate by my map


Solution

  • Yes, you should iterate through your Maps.

    ProductSettings settings = /* ... */;
    
    Set<ProductType> enabledProductTypes = EnumSet.noneOf(ProductType.class);
    
    for (Map.Entry<ProductType, Predicate<ProductSettings>> entry : mapGetter) {
        ProductType type = entry.getKey();
        Predicate<ProductSettings> enabled = entry.getValue();
    
        if (enabled.test(settings)) {
            enabledProductTypes.add(type);
        }
    }
    

    And:

    ProductSettings settings = /* ... */;
    Set<ProductType> enabledProductTypes = /* ... */
    
    for (Map.Entry<ProductType, BiConsumer<ProductSettings, Boolean>> entry : mapSetter) {
        ProductType type = entry.getKey();
        BiConsumer<ProductSettings, Boolean>> setter = entry.getValue();
    
        setter.accept(settings, enabledProductTypes.contains(type));
    }