guava 函数式编程三兄弟之Function的用法

先上guavaFunction的接口:
public interface Function<F, T> {
 
  T apply(@Nullable F input);

  boolean equals(@Nullable Object object);
}
该接口提供两个方法,一个是apply,一个是equals.apply方法接受一个input参数返回T。
该接口主要用于转换函数。给我一个输入,我转换为另外需要的输出。
例如:
 public class DateFunction implements Function<String, Date>{

	@Override
	public Date apply(String input) {
		try {
			return new SimpleDateFormat("yyyy-MM-dd").parse(input);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		
		return null;
	}

}
将一个String格式化为一个Date.这样写有什么好处?
这样写可以简化利用匿名内部类的形式简化某些书写,你不需要再建立类了直接可以这样:new Function<String, Date>() {

			@Override
			public Date apply(String input) {
				return null;
			}
		}

Functions封装了一些Function的实现:
比较常用的有:
private static class FunctionForMapNoDefault<K, V> implements Function<K, V>, Serializable {
    final Map<K, V> map;

    FunctionForMapNoDefault(Map<K, V> map) {
      this.map = checkNotNull(map);
    }

    @Override
    public V apply(@Nullable K key) {
      V result = map.get(key);
      checkArgument(result != null || map.containsKey(key), "Key '%s' not present in map", key);
      return result;
    }

    @Override
    public boolean equals(@Nullable Object o) {
      if (o instanceof FunctionForMapNoDefault) {
        FunctionForMapNoDefault<?, ?> that = (FunctionForMapNoDefault<?, ?>) o;
        return map.equals(that.map);
      }
      return false;
    }

    @Override
    public int hashCode() {
      return map.hashCode();
    }

    @Override
    public String toString() {
      return "Functions.forMap(" + map + ")";
    }

    private static final long serialVersionUID = 0;
  }
从map中根据key获取值获取不到就抛出异常。
另外一个比较常用的方法为:
 private static class ForMapWithDefault<K, V> implements Function<K, V>, Serializable {
    final Map<K, ? extends V> map;
    final V defaultValue;

    ForMapWithDefault(Map<K, ? extends V> map, @Nullable V defaultValue) {
      this.map = checkNotNull(map);
      this.defaultValue = defaultValue;
    }

    @Override
    public V apply(@Nullable K key) {
      V result = map.get(key);
      return (result != null || map.containsKey(key)) ? result : defaultValue;
    }

    @Override
    public boolean equals(@Nullable Object o) {
      if (o instanceof ForMapWithDefault) {
        ForMapWithDefault<?, ?> that = (ForMapWithDefault<?, ?>) o;
        return map.equals(that.map) && Objects.equal(defaultValue, that.defaultValue);
      }
      return false;
    }

    @Override
    public int hashCode() {
      return Objects.hashCode(map, defaultValue);
    }

    @Override
    public String toString() {
      // TODO(cpovirk): maybe remove "defaultValue=" to make this look like the method call does
      return "Functions.forMap(" + map + ", defaultValue=" + defaultValue + ")";
    }

    private static final long serialVersionUID = 0;
  }
根据key获取值,假如不存在key就用默认的值代替。

猜你喜欢

转载自chen-sai-201607223902.iteye.com/blog/2367442