当谓词匹配时有条件地转换Stream元素
答
如果你需要做这个有很多,你可以创建一个函数来为你做你应该只使用一个映射值
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
用一个简单的循环? –
http://stackoverflow.com/q/42029357/2711488 – Holger