[英]How to perform some mathematical operation on some specific elements of a list using java 8?
我有一個這樣的整數列表:
List<Integer> list = new ArrayList(Arrays.asList(30,33,29,0,34,0,45));
我想從每個元素中減去1除了0。
我嘗試過一些方法,比如應用Java 8的過濾器,但它從列表中刪除了零值。 我嘗試應用為stream API提供的其他方法,如foreach() or .findFirst(),.findAny()
但它不起作用。
List<Integer> list2 = list.stream().filter(x -> x > 0).map(x -> x - 1).collect(Collectors.toList());
//list.stream().findFirst().ifPresent(x -> x - 1).collect(Collectors.toList()); //This is giving error
list.stream().forEach(x ->x.); //How to use this in this case
實際結果: [29,32,28,-1,33,-1,44]
預期成果: [29,32,28,0,33,0,44]
list.stream()
.map(x -> x == 0 ? x : x - 1)
.collect(Collectors.toList());
在示例中,您可以使用Math.max
方法:
list.stream()
.map(x -> Math.max(0, x - 1))
.collect(Collectors.toList());
在你的情況下:
list.stream() // 1,2,0,5,0
.filter(x -> x > 0) // 1,2,5
.map(x -> x - 1) // 0,1,4
.collect(Collectors.toList()); // will return list with three elements [0,1,4]
非流版本使用replaceAll
list.replaceAll(x -> x != 0 ? x - 1 : x);
另一種方案:
IntStream.range(0, list.size())
.map(e -> list.get(e) == 0 ? list.get(e) : list.get(e) - 1)
.forEach(System.out::println);
輸出:
29 32 28 0 33 0 44
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.