我想创建一个" Planet"来自.csv文件的对象使用PlanetBuilder和流。我到目前为止只能读到csv文件和每行,创建一个Planet对象,但不幸的是我不知道如何将构造函数值赋给对象,所以它基本上只是创建一个空行星每一行的对象。有人可以告诉我如何为每一行分配值吗?
创建对象后,我将它们添加到列表行星
这是创建新行星对象的方法。
public List<Planet> csvDataToPlanets(String filePath) {
List<Planet> planets = new ArrayList<>();
try (Stream<String> lines = Files.lines(Paths.get(filePath))) {
List<List<String>> places = lines.skip(1).map(line -> Arrays.asList(line.split(","))).collect(Collectors.toList());
places.forEach(place -> new PlanetBuilder().createPlanet());
} catch (IOException e) {
e.printStackTrace();
}
return planets;
}
这是CSV文件。
planet_name,inhabitants,has_stargate,has_dhd,teams_visited
Abydos,0,True,False,[sg-1]
Adara II,117778380,True,True,[sg-1]
Adora,0,False,False,[sg-1]
Alaris,13663,True,True,[sg-1]
Alebran's planet,186402846,False,False,[sg-1; sg-6]
Alpha Site,460849025,True,True,[sg-1; sg-4]
Altair,8087,False,False,[sg-1; sg-2]
Amon Shek,0,True,True,[sg-1; sg-9]
Amra,467925616,True,False,[sg-1]
Apophis's training camp,10188,True,True,[sg-1]
Ardena,13693,True,True,[sg-1; sg-5]
Argos,0,True,True,[sg-1]
Arkad's planet,257318689,True,False,[sg-1; sg-14]
Arkhan's planet,464136466,False,False,[sg-1]
以及我的Planet类和Planetbuilder类
public class Planet {
private String name;
private long inhabitants;
private boolean stargateAvailable;
private boolean dhdAvailable;
private List<String> teamsVisited;
public Planet(String name, long inhabitants, boolean stargateAvailable, boolean dhdAvailable, List<String> teamsVisited) {
}
public String getName() {
return name;
}
public long getInhabitants() {
return inhabitants;
}
public boolean isStargateAvailable() {
return stargateAvailable;
}
public boolean isDhdAvailable() {
return dhdAvailable;
}
public List<String> getTeamsVisited() {
return teamsVisited;
}
@Override
public String toString() {
return name;
}
public class PlanetBuilder {
private String name;
private long inhabitants;
private boolean stargateAvailable;
private boolean dhdAvailable;
private List<String> teamsVisited;
public PlanetBuilder Name(String name) {
this.name = name;
return this;
}
public PlanetBuilder Inhabitants(long inhabitants) {
this.inhabitants = inhabitants;
return this;
}
public PlanetBuilder StargateAvailable(boolean stargateAvailable) {
this.stargateAvailable = stargateAvailable;
return this;
}
public PlanetBuilder DhdAvailable(boolean dhdAvailable) {
this.dhdAvailable = dhdAvailable;
return this;
}
public PlanetBuilder TeamsVisited(List<String> teamsVisited) {
this.teamsVisited = teamsVisited;
return this;
}
public Planet createPlanet() {
return new Planet(name, inhabitants, stargateAvailable, dhdAvailable, teamsVisited);
}
答案 0 :(得分:1)
最简单的答案是扩展places.forEach(place ->...)
调用中的逻辑,以便从place
(值为List<String>
中获取每个值并添加为您的构建器调用每个属性(根据需要解析它们)。例如。 places.forEach(place -> new PlanetBuilder().Name(place.get(0)).createPlanet());
(在这种情况下不需要解析)
然而,这绝对不是最好的解决方案。
理想情况下,您可以使用像http://beanio.org/或http://flatworm.sourceforge.net/这样的库来为您处理解组。