Tuesday, 5 April 2016

Null check in Java 8


Now java is becoming more advanced and programmer friendly with java 8.

now to check null we no need custom classes or if conditions.

Solution:

/*{
   "one": "two",
   "key": "value"
}*/

String body= "Sample Json String Shown above";

JSONObject on = new JSONObject(body);
Map<String,String> map = new HashMap<>();
       
        Set<String> keySet = new HashSet<>();

        Optional.ofNullable(keySet).ifPresent(x-> x.forEach(z-> map.put(z, on.getString(z))));

Steps:
1. Checking null (Optional.ofNullable(keySet))
2. If not null or actual object present (ifPresent)
3. Iterate over collection (forEach)
4. Filling Map

No comments:

Post a Comment

Please comment here