Created
October 6, 2022 17:02
-
-
Save vanduc1102/dc1e185cae8363aa08eb7133653f8e05 to your computer and use it in GitHub Desktop.
Java Higher Order Function sample
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.pragmatists.blog.events.application; | |
import java.util.Random; | |
import java.util.function.Function; | |
import java.util.function.Supplier; | |
public class HOFSampleToro { | |
public static void main(String[] args) { | |
System.out.println("Hello world"); | |
testLikeAPro(); | |
} | |
private static void testLikeAPro(){ | |
String searchName = "toro dep trai 10-11"; | |
Supplier<Response> lazySearchName = () -> { | |
SearchApi searchAPI = new SearchApi(); | |
return searchAPI.searchConKet(searchName); | |
}; | |
Response response = requestWithTry().apply(lazySearchName); | |
System.out.println("status: "+ response.status + "; data:"+response.data); | |
} | |
private static Function<Supplier<Response>, Response> requestWithTry(){ | |
return (request) ->{ | |
int count = 0; | |
while(true){ | |
System.out.println("tried: "+ ++count); | |
try { | |
Thread.sleep(1000); | |
} catch (InterruptedException e) { | |
throw new RuntimeException(e); | |
} | |
Response response = request.get(); | |
if(response.status == 200){ | |
return response; | |
} | |
} | |
}; | |
} | |
static class RequestAPI{ | |
Response get(String url){ | |
int[] statuses = new int[]{200, 400, 500}; | |
Random random = new Random(); | |
return new Response(statuses[random.nextInt(statuses.length)], "response of: " + url); | |
} | |
} | |
static class SearchApi extends RequestAPI { | |
Response searchConKet(String name) { | |
System.out.println("Search conket: "+ name); | |
return get("?conket=where&name="+name); | |
} | |
} | |
static class Response { | |
int status; | |
String data; | |
public Response(int status, String data) { | |
this.status = status; | |
this.data = data; | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
References:
https://medium.com/@knoldus/functional-java-lets-understand-the-higher-order-function-1a4d4e4f02af
https://www.baeldung.com/java-8-functional-interfaces