簡體   English   中英

語法混亂:設置 <String> set = people.stream()。map(Person :: getName).collect(Collectors.toCollection(TreeSet :: new))

[英]Confusion over the syntax: Set<String> set = people.stream().map(Person::getName).collect(Collectors.toCollection(TreeSet::new))

我正在嘗試學習Java Set接口,並且在線上遇到了以下代碼,我理解該代碼的目的是將Collection<Object>轉換為TreeSet ,但是由於語法是對我來說復雜而陌生。 有人可以逐步引導我完成此過程嗎?

Set<String> set = people.stream()
                        .map(Person::getName)
                        .collect(Collectors.toCollection(TreeSet::new));

而且,在哪種情況下,我們應首選上述語法而不是下面的語法?

Set<Integer> s1 = new TreeSet(c1); //where c1 is an instance of Collection interface type

people.stream()

吸引一組人並獲得一個流。

.map(Person::getName)

招募人員並在每個人員上調用getName方法,並返回包含所有結果的列表。 這將等同於

for(Person person : people){
    setOfNames.add(person.getName())
}

.collect(Collectors.toCollection(TreeSet::new));

接收字符串流並將其轉換為一組。


當您需要應用多個轉換時,流非常有用。 如果您使用並行流,它們也可以很好地執行,因為每個轉換(在您的情況下為每個getName )都可以並行執行而不是順序執行。

peopele.stream()創建元素流.map(Person :: getName)從people集合中獲取每個對象,並調用getName,將其轉換為字符串,然后.collect(Collectors.toCollection(TreeSet :: new))-收集這些String元素並從中創建一個TreeSet。

希望清楚

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM