# 用Java流求和

## 2.使用`Stream.reduce()`

`Stream.reduce()`是**對stream的元素進行歸約**的終端操作

``````List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5);

Integer sum = integers.stream()

.reduce(0, (a, b) -> a + b);``````

``````List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5);

Integer sum = integers.stream()

.reduce(0, Integer::sum);``````

``````public class ArithmeticUtils {

public static int add(int a, int b) {

return a + b;

}

}
``````

``````List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5);

Integer sum = integers.stream()

``````

## 3.使用`Stream.collect()`

``````List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5);

Integer sum = integers.stream()

.collect(Collectors.summingInt(Integer::intValue));``````

## 4.使用`IntStream.sum()`

Stream API為我們提供了**`mapToInt()`中間操作，該操作將我們的流轉換為`IntStream`對象**。

``````List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5);

Integer sum = integers.stream()

.mapToInt(Integer::intValue)

.sum();``````

## 5.將`Stream#sum`與`Map`

``````Integer sum = map.values()

.stream()

.mapToInt(Integer::valueOf)

.sum();``````

## 6.對對象使用`Stream#sum`

``````public class Item {

private int id;

private Integer price;

public Item(int id, Integer price) {

this.id = id;

this.price = price;

}

// Standard getters and setters

}
``````

``````Item item1 = new Item(1, 10);

Item item2 = new Item(2, 15);

Item item3 = new Item(3, 25);

Item item4 = new Item(4, 40);

List<Item> items = Arrays.asList(item1, item2, item3, item4);``````

``````Integer sum = items.stream()

.map(x -> x.getPrice())

``````
``````Integer sum = items.stream()

.map(x -> x.getPrice())

.reduce(0, Integer::sum);``````
``````Integer sum = items.stream()

.map(item -> item.getPrice())

.reduce(0, (a, b) -> a + b);``````
``````Integer sum = items.stream()

.map(x -> x.getPrice())

.collect(Collectors.summingInt(Integer::intValue));``````
``````items.stream()

.mapToInt(x -> x.getPrice())

.sum();``````

## 7.對`String`使用`Stream#sum`

``````String string = "Item1 10 Item2 25 Item3 30 Item4 45";

Integer sum = Arrays.stream(string.split(" "))

.filter((s) -> s.matches("\\d+"))

.mapToInt(Integer::valueOf)

.sum();``````