![](/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.