[英]Is there a more elegant way to get random not used item from list using java 8?
[英]Java: is there more elegant way to extract a new list from an existing list using reduce?
我正在嘗試獲取元素列表,對這些元素的一部分進行一些操作,並將這些操作的 output 放在一個新列表中。 我只想在列表中進行一次迭代。
我發現這樣做的唯一方法是:
List<Integer> newList = numList.stream().reduce(new ArrayList<Integer>(),
(acc, value) -> {
if (value % 2 == 0) {
acc.add(value * 10);
}
return acc;
},
(l1, l2) -> {
l1.addAll(l2);
return l1;
}
);
如您所見,這非常麻煩。
我當然可以使用filter
然后map
,但在這種情況下我迭代列表兩次。
在其他語言(例如Javascript)中,這種reduce操作非常簡單,例如:
arr.reduce((acc, value) => {
if (value % 2 == 0) {
acc.push(value * 10);
}
return acc;
}, new Array())
驚人。 我在想,Java 是否有更好的減少版本,或者我編寫的 Java 代碼是執行此類操作的最短方法。
我當然可以使用過濾器和它們 map,但在這種情況下,我將列表迭代兩次。
這不是真的。 Stream
的元素迭代一次,不管你有多少中間操作。
此外,執行可變歸約的正確方法是使用collect
:
List<Integer> newList =
numList.stream()
.filter(v -> v % 2 == 0)
.map(v -> v * 10)
.collect(Collectors.toList());
您所做的與函數式編程相反,因為您使用函數只是為了獲得副作用。
您可以簡單地不使用 reduce 使其更加明確:
List<Integer> newList = numList.stream()
.filter(value -> value % 2 == 0)
.map(value -> value * 10)
.collect(Collectors.toList());
編輯: Stream
根據定義對集合進行一次迭代。 根據javadoc :
stream 應該只運行一次(調用中間或終端 stream 操作)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.