# count()、peek()、mapToInt()用法
**Question:**
```java=
public static void main(String[] args) {
List<String> listVal = Arrays.asList("Joe", "Paul", "Alice", "Tom");
System.out.println(listVal.stream().filter(x -> x.length()>3).count()); //n1
}
```
Console: 印出字數大於3的count
```Console=
2
```
### Which code fragment, when inserted at line n1, enables the code to print the count of string elements whose length is greater than three?
**A. listVal.stream().filter(x -> x.length()>3).count()**
B. listVal.stream().map(x -> x.length()>3).count()
C. listVal.stream().peek(x -> x.length()>3).count().get()
D. listVal.stream().filter(x -> x.length()>3).mapToInt(x -> x).count()
- [x] **Answer: A**
:::info
選項A,用filter方法只保留字串長度大於三的元素,所以剩下來的元素數量為2。是正確答案。
選項B,用map方法將所有元素轉為boolean,數量依然為4。
選項C,peak方法的用法不正確。參數不能有回傳值
選項D,mapToInt方法的用法不正確。 mapToInt的回傳值必須要是int,應改成mapToInt(x->x.length())
:::
---
**Question:**
```java=
public static void main(String[] args) {
List<String> valList = Arrays.asList("","George","","John","Jim");
Long newVal = valList.stream().filter(x->!x.isEmpty()).count();
System.out.println(newVal);
}
```
Console:
```Console=
3
```
---
:::warning
### peek的操作方法
[參考網站](https://kknews.cc/zh-tw/code/2nnlkb9.html)
---
### peek 操作演示
```java=
Stream<String> stream = Stream.of("hello", "felord.cn");
stream.peek(System.out::println);
```
如果你測試了上面的代碼你會發現不會按照邏輯跑。
這是因為stream的生命周期有三個階段:
- 起始生成階段。
- 中間操作會逐一獲取元素並進行處理。 可有可無。所有中間操作都是惰性的,因此,stream在管道中流動之前,任何操作都不會產生任何影響。
- 終端操作。通常分為 最終的消費 (foreach 之類的)和 歸納 (collect)兩類。還有重要的一點就是終端操作啟動了stream在管道中的流動。
所以應該改成下面:
```java=
Stream<String> stream = Stream.of("hello", "felord.cn");
List<String> strs= stream.peek(System.out::println).collect(Collectors.toLIst());
```
:::
**Question:**
```java=
List<Integer> values = Arrays.asList(1,2,3);
values.stream().map(n->n*2).peek(System.out::print).count();
```
Console:
```Console=
246
```
如果把題目的count()拿掉,則peek不會做任何事
---
Example:
```java=
List<Integer> prices = Arrays.asList(3,4,5);
prices.stream()
.filter(e -> e>4)
.peek(e -> System.out.println("Price "+e)) //line n1
.map(n -> n-1) //line n2
.peek(n -> System.out.println("New Price "+n));//line n3
```
## Which modification enables the code to print Price 5 New Price 4?
A. Replace line n2 with .map (n -> System.out.println ("New Price" + n ?)) and remove line n3
B. Replace line n2 with .mapToInt (n -> n ?1);
C. Replace line n1 with .forEach (e -> System.out.print ("Price" + e))
**D. Replace line n3 with .forEach (n -> System.out.println ("New Price" + n));**
- [x] **Answer: D**
---
###### tags: `ocpjp`