“This is the 11th day of my participation in the Gwen Challenge in November. See details: The Last Gwen Challenge in 2021.”

Recently, the company has been conducting code reviews with a lot of fanfare, and it has discovered its own bad code habits. Accidentally stumbled into the company’s encapsulated method of filtering the map collection and discovered the Stream. So I looked into it. And the original code was reconstructed with Optional again

Description of original method

Filter criteria Map object, filter out null and empty string operations

  • 1. Use filter to filter null and empty strings
  • 2. Use map to convert elements contained in Stream using the given conversion function
  • 3. Collect Collects information into a map

Since the company’s code is not suitable to show myself, I wrote a similar simple method to imitate the company, and then step by step optimization

Custom map tool class processing methods

// The code here is modified from the original code, Public static map <String, Object> parseMapForFilter(map <String, Object> parseMapForFilter) Object> map) { if (map == null) { return null; } else { map = map.entrySet().stream() .filter((e) -> checkValue(e.getValue())) .collect(Collectors.toMap( (e) -> (String) e.getKey(), (e) -> e.getValue() )); } return map; } private static boolean checkValue(Object object) { if (object instanceof String && "".equals(object)) { return false; } if (null == object) { return false; } return true; }Copy the code

Under test

    public static void main(String[] args) {
        Map<String,Object> params = new HashMap<>(16);

        params.put("a","");
        params.put("b",null);
        params.put("c","c");

        params = MapUtil.parseMapForFilter(params);
        System.out.println(params);
        System.out.println(MapUtil.parseMapForFilter(null));
    }
    
Copy the code

The output

{c=c}
null

Copy the code

Optimize the parseMapForFilter method by adding the Optional class

public static Map<String, Object> parseMapForFilterByOptional(Map<String, Object> map) {

        return Optional.ofNullable(map).map(
                (v) -> {
                    Map params = v.entrySet().stream()
                            .filter((e) -> checkValue(e.getValue()))
                            .collect(Collectors.toMap(
                                    (e) -> (String) e.getKey(),
                                    (e) -> e.getValue()
                            ));

                    return params;
                }
        ).orElse(null);
    }
    
Copy the code

Does it feel clearer?

Test the

    public static void main(String[] args) {
        Map<String, Object> params = new HashMap<>(16);

        params.put("a", "");
        params.put("b", null);
        params.put("c", "c");

        params = MapUtil.parseMapForFilterByOptional(params);

        System.out.println(params);
        System.out.println(MapUtil.parseMapForFilterByOptional(null));
    }
Copy the code

The results of

{c=c}
null
Copy the code

Optimize the checkValue method

private static boolean checkValueByOptional(Object object) { return (Boolean) Optional.ofNullable(object) .filter((e) ->  e instanceof String && e.equals("") ? false : true) .orElse(false); }Copy the code

conclusion

Does it feel like lambda is a little bit more straightforward, no longer full of if judgments? But if you write it for the first time, you’re not used to it, and WHEN I first started writing it, IT was very awkward, I didn’t know how to write it. Try it little by little. The details of the basis are not covered here.

It just feels like the map is handled pretty well. And the actual work is used in more places.