Java8 functional programming practice

The business scenario

The front end passes one or more keys configured by the current merchant and obtains data corresponding to each key from the server.

Request:

var url = http://localhost:8080/api/merchant/1/metadata? modules=shop,paymentType,user,userLevel
Copy the code

Response:

{
	"shop": []."paymentType": []."user": []."userLevel":[]
}
Copy the code

Part of core code

@Service
public class MetadataServiceImpl {

    // Set of metadata manipulation functions
    private Map<String, Function<Long, Object>> metaFunMap = new HashMap<>();

    @Autowired
    public MetadataServiceImpl(a) {
        metaFunMap.put("shop".this::getShop);
        metaFunMap.put("paymentType".this::getPaymentType);
        metaFunMap.put("user".this::getUser);
        metaFunMap.put("userLevel".this::getUserLevel);
    }
    
    private List<Shop> getShop(Long merchantId){
        // Query Shop data from database
        return null;
    }

    private List<PaymentType> getPaymentType(Long merchantId){
        // Query PaymentType data from the database
        return null;
    }

    private List<User> getUser(Long merchantId){
        // Query User data from the database
        return null;
    }

    private List<UserLevel> getUserLevel(Long merchantId){
        // Query UserLevel data from the database
        return null;
    }

    /** * Dynamically fetch merchant metadata - parallel operation */
    public MetaResponse getMetadata(Long merchantId, List<String> modules) {
        // Store the result of each key query in JSON
        JSONObject content = new JSONObject();
        // Query data for each key in parallel
        modules.parallelStream().forEach(module -> content.put(module, metaFunMap.get(meta).apply(merchantId)));
        // Response result
        return newMetaResponse(content); }}Copy the code

Train of thought

  1. Define a Map, key: the unique identification of each data module, consistent with the front-end negotiation, value: the function to obtain the data of each module
  2. The Map is initialized when the current Bean is instantiated
  3. When the front end requests, the parallel stream is used to traverse each module (key), take out the function to be executed from Map, execute it, store the execution result in JSON, and finally respond to the front end

I’ll share other fun java8 uses later.