I'm new to Java 8 and need help to analyze if the BiFunction implementation using lambda can be reduced to a single line of code.

I'm receiving a JSON response from a REST API in the form of a String, which I want to store in a Hashmap using Gson and then my function should return the value given the Key.

Map<String,String> map = new HashMap<>();
BiFunction<String,String,String> getValueFromResponseWithKey = (s1,s2)-> {
            Map<String,String> str =gson.fromJson(response,map.getClass());
            return str.get(s2);};

It would be great if I could find a single line implementation of the getValueFromResponseWithKey function.

1 Answers

Rajkumar Natarajan On Best Solutions

It should be like below. You may need to add simple casting like this-

BiFunction<String,String,String> getValueFromResponseWithKey = 
        (s1,s2) -> ((Map<String, String>) gson.fromJson(response,map.getClass())).get(s2);