在java 8中为Map添​​加非值的优雅方法?

bra*_*orm 3 java hashmap guava java-8

我正在使用不可变的地图

public Map<String,String> getMap(){
        return ImmutableMap.<String,String>builder()
                .put("FOO",getFooType())
                .put("BAR", getBarType())
                .build();
    }
Run Code Online (Sandbox Code Playgroud)

在某些情况下,getFooType()getBarType()将返回null.这会导致异常被抛出 com.google.common.collect.ImmutableMap.我想知道是否有一种优雅的方式来填充地图只有非空和非空字符串.

我对任何Map实现都没问题,不仅仅局限于番石榴库.

我可以取消以下内容

Map<String,String> map = new HashMap<>();

String fooType = getFooType();
String barType = getBarType();

if (fooType!=null && fooType.length()>0){
    map.put("FOO", fooType);
}

if (barType!=null && barType.length()>0){
     map.put("BAR", barType);
}
Run Code Online (Sandbox Code Playgroud)

由于我有许多键要添加到地图中,因此这种if-checks会使代码变得不漂亮.我想知道是否有任何优雅的方式来做到这一点.

我正在为我的项目使用Java 8.

Nir*_*evy 7

您可以使用Optional地图的值:

public Map<String,Optional<String>> getMap(){
  return ImmutableMap.<String,Optional<String>>builder()
    .put("FOO",Optional.<String>ofNullable(getFooType()))
    .put("BAR", Optional.<String>ofNullable(getBarType()))
    .build();
}
Run Code Online (Sandbox Code Playgroud)

这样,地图将存储包裹字符串的可选对象,当您从地图获取值时,使用map.get(key).orElse(DEF_VALUE);- 这将为具有空值的那些提供DEF_VALUE.

在这里看到更多