2016-03-04 22 views

回答

12

这将仅在List工作,而不是在一个Collection,因为后者没有更换或设置元素的概念。

但考虑到一个List,这是很容易做到你想要用的是什么List.replaceAll()方法:

List<String> list = Arrays.asList("a", "b", null, "c", "d", null); 
list.replaceAll(s -> s == null ? "x" : s); 
System.out.println(list); 

输出:

[a, b, x, c, d, x] 

如果你想有一个变化,需要一个谓语,你可以写一点帮手功能来做到这一点:

static <T> void replaceIf(List<T> list, Predicate<? super T> pred, UnaryOperator<T> op) { 
    list.replaceAll(t -> pred.test(t) ? op.apply(t) : t); 
} 

这将被调用如下:

replaceIf(list, Objects::isNull, s -> "x"); 

给出相同的结果。

+0

感谢斯图尔特纠正这个问题,并给出了一个干净优雅的答案。 –

0

这可以试试这个:

list.removeAll(Collections.singleton(null)); 
+1

他想替换它们而不是删除它们 – achabahe

2

你需要一个简单的地图功能:

Arrays.asList(new Integer[] {1, 2, 3, 4, null, 5}) 
.stream() 
.map(i -> i != null ? i : 0) 
.forEach(System.out::println); //will print: 1 2 3 4 0 5, each on a new line 
2

试试这个。

public static <T> void replaceIf(List<T> list, Predicate<T> predicate, T replacement) { 
    for (int i = 0; i < list.size(); ++i) 
     if (predicate.test(list.get(i))) 
      list.set(i, replacement); 
} 

List<String> list = Arrays.asList("a", "b", "c"); 
replaceIf(list, x -> x.equals("b"), "B"); 
System.out.println(list); 
// -> [a, B, c] 
+0

这似乎是一个很好的解决方案 –