簡體   English   中英

我想知道,有沒有更有效的方法來做到這一點

[英]I want to know , Is there a more efficient way to do this

有一個方法saveCountryIslands帶有String數組參數。 有一個實體是國家和島嶼。

我一直在嘗試使用jpa .save()保存提供的島嶼名稱列表。

現有的方法主體已經在工作(您可以在下面的代碼中看到)。

有更有效的方法嗎?

private void saveCountryIslands(String[] islandNames){

    List<Islands> listOfIsland = new ArrayList<>();
    Country country=new Country();

    Stream.of(islandNames).distinct().forEach(islandNamesFromArray -> {
      Islands islands = new Islands();
      islands.setIslandName(islandNamesFromArray);
      listOfIsland.add(islands);
    });

    country.setCountryIslands(listOfIsland);
    countryRepository.save(country);

}

您可以通過以下方式使用構造函數來帶來可讀性的一個小變化:

    public Islands(String name) {
        this.name = name;
    }

然后將現有代碼重構為:

    List<Islands> listOfIsland = Stream.of(islandNames)
            .distinct()
            .map(Islands::new)
            .collect(Collectors.toList()); // collect 'toSet' depending on compatibility

暫無
暫無

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

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