2016-03-04 42 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

這似乎是一個很好的解決方案 –