Skip to content

Instantly share code, notes, and snippets.

@vanduc1102
Created October 6, 2022 17:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vanduc1102/dc1e185cae8363aa08eb7133653f8e05 to your computer and use it in GitHub Desktop.
Save vanduc1102/dc1e185cae8363aa08eb7133653f8e05 to your computer and use it in GitHub Desktop.
Java Higher Order Function sample
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;
}
}
}