Tuesday, August 1, 2017

Java Lambdas Tips

Creating a lookup method for an Enum



Without lambdas:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public enum Type {
      
     INFO,
     WARNING,
     ERROR;
 
     final static Map<String, Type> lookup = new HashMap<String, Type>();
      
     static {
      for(Type type : Type.values()) {
       lookup.put(type.name().toLowerCase(), type);
      }
     }
 
        
     public static Type of(String value){
         Type val = lookup.get(value == null ? null : value.toLowerCase());
         if(val == null){
             val = ERROR;
         }
         return val;
     }
}

With lambda:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public enum Type {
     INFO,
     WARNING,
     ERROR;
 
     final static Map<String, Type> lookup = Arrays.stream(Type.values())
          .collect(Collectors.toMap(t -> t.name().toLowerCase(), Function.identity()));
 
     public static Type of(String value){
         Type val = lookup.get(value == null ? null : value.toLowerCase());
         if(val == null){
            val = ERROR;
         }
         return val;
     }
}