I have a code that works fine, but it looks too big as it has repetitive line of codes, can someone help me to make it shorter?
public void writeToFile(String file)
{
try
{
PrintWriter pWrite = new PrintWriter(file);
pWriter.println("[Auto data]");
for (Auto line : autoMap.values())
{
if (line instanceof Auto)
{
String getLine = line.writeData(file);
pWrite.println(getLine);
}
}
pWriter.println();
pWriter.println("[Nature data]");
for (Nature line : natureMap.values())
{
if (line instanceof Nature)
{
String getLine = line.writeData(file);
pWrite.println(getLine);
}
}
pWriter.println();
pWriter.println("[Sport data]");
for (Sport line : sportMap.values())
{
if (line instanceof Sport)
{
String getLine = line.writeData(file);
pWrite.println(getLine);
}
}
pWriter.println();
pWriter.println("[Animal data]");
for (Animal line : animalMap.values())
{
if (line instanceof Animal)
{
String getLine = line.writeData(file);
pWrite.println(getLine);
}
}
pWrite.close();
}
// catch block omitted
}
writeData method example class Sport:
public class Sport
{
// codes omitted
public String writeData(String file)
{
return title + type + cost + location;
}
// codes omitted
}
As you have noticed the for loops are necessary to subdivide data in order when writing to a file, but doing so, it made the code longer and repetitive, I cannot think of an efficient way to make it shorter.