---
description: 開發應用日誌
---

# Stream 應用

### Object list stream cast class

```java
public static void main(String[] args) throws JsonProcessingException, ParseException {	
	List<Object> list = new ArrayList<>();
	for(long i = 0; i < 100; i++){
		list.add(new ViewCounts().setMemberId(i));
	}

	calculateProcess("has Filter >", () -> {
		list.stream()
		.filter(ViewCounts.class::isInstance)
		.map(ViewCounts.class::cast)
		.forEach(o -> System.out.println("2 > memberId:" + o.getMemberId()));
	});
	// has Filter > duration: 19(ms)

	calculateProcess("no Filter >", () -> {
		list.stream()
		.map(o -> (ViewCounts) o)
		.forEach(o -> System.out.println("memberId:" + o.getMemberId()));
	});
	// no Filter > duration: 17(ms)
}

interface calculateProcess {
	void calculate();
}

public static void calculateProcess(String methodName, calculateProcess process) {
	long start = System.nanoTime();
	if (Objects.nonNull(process))
		process.calculate();
	long end = System.nanoTime();
	long duration = TimeUnit.NANOSECONDS.toMillis(end - start);
	System.out.println(methodName + " duration: " + duration + "(ms)");
}
```

兩種方法經過效能測試幾乎一樣，但第一種寫法比較穩健，可以避&#x514D;**`ClassCastException`**&#x7684;問題發生。

#### Summing Numbers - 統計數值

```java
List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5);
Integer sum = integers.stream()
  .mapToInt(Integer::intValue)
  .sum();
  
System.out.println(sum);
// console log :15

// BigDecimal 加總辦法
List<BigDecimal> list = List.of(BigDecimal.ONE, BigDecimal.ZERO, BigDecimal.TEN, 
                                new BigDecimal(100), new BigDecimal(200));
BigDecimal sum = list.stream().reduce(BigDecimal.ZERO, BigDecimal::add);
System.out.println(sum);
// console log :311
```

#### LongStream - 簡易迴圈操作

```java
String str = LongStream.rangeClosed(0, 100)
                                .mapToObj(o -> String.valueOf(o))
                                .collect(Collectors.joining(",", "[", "]"));

// console log:[0,1,2,3,4,5,.....,97,98,99,100]
// java.util.stream package 底下還有一些實用的物件可以使用，大大減少測試及開發上的時間。
```

#### 如果我有看到很棒的寫法，會持續更新....

