# 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 底下還有一些實用的物件可以使用，大大減少測試及開發上的時間。
```

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


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://xu-min-chang.gitbook.io/caster-develop-note/java/java-8/stream-ying-yong.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
