簡體   English   中英

如何在Java 8中壓縮以下內容

[英]How to condense the following in Java 8

一輛Car有多個制造商,我想將所有制造商集合在一個Set

例如:

class Car {
    String name;
    List<String> manufactures;
}  

object sedan -> { ford, gm, tesla }
object sports -> { ferrari, tesla, bmw }
object suv -> { ford, bmw, toyota }

現在,我需要創建包含所有制造商的輸出(無冗余)

我試過了:

carList.stream().map(c -> c.getManufacturers()).collect(Collectors.toSet());

這給了我一個ListSet ,但是我需要擺脫嵌套,而只創建一個Set (非nested)。

[編輯]如果某些對象對制造商而言具有“空”值並且我們要防止NPE怎么辦?

使用flatMap

Set<String> manufactures =
    carList.stream()
           .flatMap(c -> c.getManufacturers().stream())
           .collect(Collectors.toSet());

如果要避免Car的制造商為null ,請添加一個過濾器:

Set<String> manufactures =
    carList.stream()
           .filter(c -> c.getManufacturers() != null)
           .flatMap(c -> c.getManufacturers().stream())
           .collect(Collectors.toSet());

僅出於簡潔目的使用方法引用的另一個變體是從Car mapList<String>filternull列表,展平流的流,然后最終收集到Set實現。

Set<String> resultSet =
          carList.stream()
                 .map(Car::getManufacturers)
                 .filter(Objects::nonNull)
                 .flatMap(List::stream)
                 .collect(Collectors.toSet());

暫無
暫無

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

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