当谓词匹配时有条件地转换Stream元素

问题描述:

我有一个流,并且只在谓词匹配时才应用方法。当谓词匹配时有条件地转换Stream元素

E.g.我想处理一个流,并用缺省值替换所有的null。什么是完成这个最好的方法?

+1

用一个简单的循环? –

+1

http://stackoverflow.com/q/42029357/2711488 – Holger

如果你需要做这个有很多,你可以创建一个函数来为你做你应该只使用一个映射值

data.stream() 
    .map(v -> v == null ? defaultValue : v) 
    ... // do whatever you need to do with it. 

编辑

public class DefaultValue<T> extends Function<T, T> P{ 
    private final T t; 
    public DefaultValue(T t){ 
     this.t. = t; 
    } 

    public T apply(T t) { 
     return t == null ? this.t : t; 
    } 
} 

data.stream() 
    .map(new DefaultValue(someValue)); 
    // Do what you need to do 

如果您想保留原来的值是做符合筛选项目,使用map三元逻辑:

  • 项目没有通过过滤器被当做返回
  • 项目通过过滤器得到转化

下面是一个例子:

Stream<String> stream = Arrays.stream(
    new String[]{"quick", null, "brown", "fox", null, "jumps"} 
); 
List<String> res = stream 
    .map(s -> s != null ? s : "<EMPTY>") 
    .collect(Collectors.toList()); 
for (String s : res) { 
    System.out.println(s); 
} 

过滤逻辑被嵌入在条件表达式内map

s -> s != null ? s : "<EMPTY>" // Using default values for null strings 

Demo.