![](/img/trans.png)
[英]I want to know if this is a good programming practise else how can i write the program more optimal and efficient
[英]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.