Given the definition of the Emp class:

public class Emp {

    private String eName;
    private Integer eAge;

    Emp(String eN, Integer eA) {
        this.eName = eN;
        this.eAge = eA;
    }

    public Integer getEAge() {
        return eAge;
    }

    public String getEName() {
        return eName;
    }
}

and code fragment:

List<Emp> li = Arrays.asList(new Emp("Sam", 20), new Emp("John", 60), new Emp("Jim", 51));
Predicate<Emp> agVal = s -> s.getEAge() > 50; //line n1
li = li.stream().filter(agVal).collect(Collectors.toList());
Stream<String> names = li.stream().map(Emp::getEName); //line n2
names.forEach(n -> System.out.print(n + " "));

What is the result?

A.

Sam John Jim

B.

John Jim

C. A compilation error occurs at line n1.
D. A compilation error occurs at line n2.

題解

程式第 32 行,串流物件的 filter 方法可以保留符合條件的元素,collect 方法可以將串流物件再轉成別的 Collection 物件,配合 Collectors 類別的 toList 方法可以將串流物件中的元素清單化,轉成 List 物件。至於元素在新的 List 物件中的順序就是原先集合物件的走訪順序,所以「Emp("John", 60)」在「Emp("Jim", 51)」之前。所以轉出來的 List 物件元素為,「Emp("John", 60), Emp("Jim", 51)」。

程式第 33 行,使用串流物件的 map 方法取代原本的元素。

程式第 34 行,輸出「John Jim 」。