I will keep it simple and easy for you guys to help me out , this is the example testfile i want to "populate" with data in this way:
1,Justinianos,Maia,2
2,Hulks,Famalicao,5
3,Padres Matias,Porto,12
4,Fanadinhos,Lisboa,4
5,Melancolitos,Vila Nova de Gaia,6
6,Ao Colinho,Sao Romao,7
7,Cavalos do Zodiaco,Cabecas de bastos,10
8,Unicorns,Aveiro,2
9,Rainbows,Coimbra,3
10,One Piece 4 ever,Folgosa,15
id,nomequadra,localidade,qtdcavalos
int,String,String,int
Then this is the class that stores the data:
/**
* Created by Ricar on 02/04/2017.
*/
public class Quadras {
private int id;
private String nomequadra;
private String localidade;
private int qtdcavalos;
public Quadras(){
id=0;
nomequadra=null;
localidade=null;
qtdcavalos=0;
}
public Quadras(int id , String nomequadra, String localidade, int qtdcavalos){
this.id = id;
this.nomequadra = nomequadra;
this.localidade = localidade;
this.qtdcavalos = qtdcavalos;
}
public int getId() {return id;}
public void setId(int id) {this.id = id;}
public String getNomequadra() {return nomequadra;}
public void setNomequadra(String nomequadra) {this.nomequadra = nomequadra;}
public String getLocalidade() {return localidade;}
public void setLocalidade(String localidade) {this.localidade = localidade;}
public int getQtdcavalos() {return qtdcavalos;}
public void setQtdcavalos(int qtdcavalos) {this.qtdcavalos = qtdcavalos;}
}
This other class joins together all the classes into arraylist for working with the data:
public class Championship {
private ArrayList<Quadras> quadras;
private ArrayList<Participante> participantes;
private ArrayList<Jornada> jornadas;
public Championship(){
this.quadras = new ArrayList<Quadras>();
this.jornadas = new ArrayList<Jornada>();
this.participantes = new ArrayList<Participante>();
}
public Championship(ArrayList<Quadras> quadras, ArrayList<Participante> participantes, ArrayList<Jornada> jornadas)
{
this.quadras = quadras;
this.participantes = participantes;
this.jornadas = jornadas;
}
public void addQuadras (Quadras s ) {quadras.add(s);}
public void printQuadras(){
System.out.println("--------Quadras-------");
for(int i = 0; i< quadras.size();i++){
System.out.println(quadras.get(i));
}
}
public void addParticipantes (Participante s ) {participantes.add(s);}
public void addJornada (Jornada s ) {jornadas.add(s);}
}
I want to populate the Championship Arraylist ,using split on the "," and then convert each substring that has difrent data then string like Integer.
After that i want to be able to reverse the process also, because i will be inserting data manualy into the txt file, but i want to be able to load from the file and store in the file.
I already have a createnewFile(); method and deleteFile(); method.
If someone could five me a hand here i would be very happy :)
Thx for spending thime reading my problem!
You can check if is a digit or a number using the code in this link:
What is the best way to tell if a character is a letter or number in Java without using regexes?
After, you can populate your objects.
Hope it helps
Related
I have data like in following logical format:
FolderID-1
FileID-1
FileID-2
FolderID-2
FileID-3
FileID-4
FileID-5
FileID-6
FolderID-3
FileID-7
FileID-8
FileID-9
FileID-10
I have list of FileID object which have FoldeID
I need to update one field in this list and need to pass to this list in other method.
I need to get FileID object based on fileid & folderid in that method.
To achieve the same I know two way
1 HashMap<folderid,List<FileID>> OR
2 HashMap<folderid, HashMap<fileid ,FileID>
Is there any other efficient way to do the same?
Thanks for looking here.
Hi I read your cmnt you can go ahead with the string key (using fileid and folder id) that will work for you. But your data comes with a nice logical structure . file id and folder id will be unique as well as a single folder will contain file having the file id is consecutive. So, My approach to solve this entirely depends on this structure.
I made two Class FileIdObj and FolderIdObj thats contains the data redarding the file and folder respectively.
public static void fileIdBasedOnFileIdAndFolderId( List<FileIdObj> fileList)
{
Map<Integer,FolderIdObj> folderIdMap=new HashMap<Integer,FolderIdObj>();
Map<Integer,FileIdObj> fileIdMap=new HashMap<Integer,FileIdObj>();
for(int i=0;i<fileList.size();i++)
{
FileIdObj file=fileList.get(i);
fileIdMap.put(file.getFileId(), file);
int folderId=file.getFolderId();
FolderIdObj folder=new FolderIdObj();
if(folderIdMap.containsKey(folderId))
{
folder=folderIdMap.get(folderId);
folder.setEndFileId(file.getFileId());
}else
{
folder.setFolderId(folderId);
folder.setStartFileId(file.getFileId());
folder.setEndFileId(file.getFileId());
}
folderIdMap.put(folderId, folder);
}
Set<Integer> set=folderIdMap.keySet();
Iterator it=set.iterator();
while(it.hasNext())
{
FolderIdObj obj=folderIdMap.get(it.next());
System.out.println("folder id: "+obj.getFolderId()+" start fileId: "+obj.getStartFileId()+
" end fileId: "+obj.getEndFileId());
}
System.out.println();
System.out.println();
set=fileIdMap.keySet();
it=set.iterator();
while(it.hasNext())
{
FileIdObj obj=fileIdMap.get(it.next());
System.out.println("file id: "+obj.getFileId()+" folder id:"+obj.getFolderId());
}
}
the list on the argument contains the file object only.
Please see below for the details of the two class.
public class FileIdObj {
private int folderId;
private int fileId;
public int getFolderId() {
return folderId;
}
public void setFolderId(int folderId) {
this.folderId = folderId;
}
public int getFileId() {
return fileId;
}
public void setFileId(int fileId) {
this.fileId = fileId;
}
}
public class FolderIdObj {
private int folderId;
private int startFileId;
private int endFileId;
public int getFolderId() {
return folderId;
}
public void setFolderId(int folderId) {
this.folderId = folderId;
}
public int getStartFileId() {
return startFileId;
}
public void setStartFileId(int startFileId) {
this.startFileId = startFileId;
}
public int getEndFileId() {
return endFileId;
}
public void setEndFileId(int endFileId) {
this.endFileId = endFileId;
}
}
Sorry for my title which is unclear, but I don't know how to say it differently.
I have an object "Rapport" which takes a couple of parameters (3 Strings and one Object). This Object "SortingParameter" takes a number of boolean arguments "boolean... args". My goal is to read lines in a text file, create an ArrayList made of these "Rapport" objects. For this, I loop through the lines:
for (String line : Files.readAllLines(Paths.get("myTxt.txt"),Charset.forName("ISO-8859-1"))) {
String[] split = line.split(";");
if(split.length>3){
rapports.add(new Rapport(split[0],split[1],split[2],new SortingParameter(PROBLEM)));
}else{
rapports.add(new Rapport(split[0],split[1],split[2]));
}
I would like to add the rest of my split[ ] tab in the object dynamically. Does anybody know how this could be cleanly done?
The rest of my code:
Rapport.java
package model;
import static model.Constant.RESSOURCES;
public class Rapport {
private String nomListe;
private String nomRessource;
private String categorie;
private SortingParameter param;
private boolean hasParameter;
public Rapport(String nomListe, String nomRessource, String categorie, SortingParameter param){
this.nomListe = nomListe;this.nomRessource = RESSOURCES + nomRessource;
this.categorie = categorie;this.param = param;
this.hasParameter = true;
}
public Rapport(String nomListe, String nomRessource, String categorie){
this.nomListe = nomListe; this.nomRessource = RESSOURCES + nomRessource;
this.categorie = categorie; this.param = null; this.hasParameter = false;
}
/** Getters **/
public String getNomListe(){return nomListe;}
public String getNomRessource(){return nomRessource;}
public String getCategorie(){return categorie;}
public boolean hasParameter(){return hasParameter;}
public SortingParameter getParam(){return param;}
}
And my SortingParameter.java:
package model;
import java.util.ArrayList;
public class SortingParameter {
private ArrayList<Boolean> paramList;
public SortingParameter(boolean... args){
paramList = new ArrayList<>();
for (boolean arg : args) {
paramList.add(arg);
}
}
public ArrayList<Boolean> getParamList(){return paramList;}
}
As you say, you want to add the rest of your split[]-tab to a Rapport-instance.
Just provide a String-Array as an attribute in your Rapport-class:
public class Rapport {
//some attributes...
private String[] eitherColumns;
//getters and setters and so on....
}
Then, when you read a line from the file, use a setter or another constructor to add the rest of the tabs to your Rapport-Instance.
You can also use a separate constructor which only gets the String-Array read from the file and let the class decide what to do with the array-elements which would be more convenient so separate your business logic from your data.
I've got a CSV in the format...
Kitten URL,Kitten Name,# of Reviews,Rating,Categories,,,,,,,,,,,,,
www.happykitten.com,happykittem.com,111746,7.8,Clothes & Fashion,Fashion Accessories,Ladies wear,Menswear,,,,,,,,,,
animedkitten.co.uk,Animed Kitten,33918,9.6,Pets,,,,,,,,,,,,,
So the first columns are Kitten URL,Kitten Name,# of Reviews,Rating then the rest are the possible categories listed as extra properties.
I'm trying to use Spring batch so I'm specifying the dumb object to represent this CSV. The first problem I've got is (using the example from Spring documentation I don't see how I can parse a CSV with spaces in the title. Is it possible to use Spring batch like this? Can I annotate each getting like in Hibernate with the title of the csv column?
My dumb object was going to be something like...
public class ImportDataObject {
private String kittenUrl;
private String kittenName;
private int numOfReviews;
public String getKittenUrl() {
return kittenUrl;
}
public void setKittenUrl(String kittenUrl) {
this.kittenUrl = kittenUrl;
}
public String getKittenName() {
return kittenName;
}
public void setKittenName(String kittenName) {
this.kittenName = kittenName;
}
public int getNumOfReviews() {
return numOfReviews;
}
public void setNumOfReviews(int numOfReviews) {
this.numOfReviews = numOfReviews;
}
}
I only really want to read the first 2 columns, append some strings, then persist the rest of the CSV.
I'm also considering the best approach to use for these multiple commas afterwards. Unfortunately this is how I've got the data and it's not something I can change.
You can implement FieldSetMapper for your object and then set it to your DefaultLineMapper. Your implementation of FieldSetMapper can work on positions and you can parse only first few positions and set it to your bean.
Here is suggestion based on code from URL you posted:
reader.setLineMapper(new DefaultLineMapper<ImportDataObject>());
setFieldSetMapper(new ImportDataObjectFieldSetMapper());
}});
setLinesToSkip(1); //skip header since read int will throw exception and I assume you do not need header info
}});
Then changes to POJO object to save list of categories:
public class ImportDataObject {
private String kittenUrl;
private String kittenName;
private int numOfReviews;
private int rating; //add getters and setters
private List<String> categories; //add getters and setters
public String getKittenUrl() {
return kittenUrl;
}
public void setKittenUrl(String kittenUrl) {
this.kittenUrl = kittenUrl;
}
public String getKittenName() {
return kittenName;
}
public void setKittenName(String kittenName) {
this.kittenName = kittenName;
}
public int getNumOfReviews() {
return numOfReviews;
}
public void setNumOfReviews(int numOfReviews) {
this.numOfReviews = numOfReviews;
}
}
And here is FieldSetMapper:
public class ImportDataObjectFieldSetMapper implements FieldSetMapper<ImportDataObject> {
#Override
public ImportDataObject mapFieldSet(final FieldSet fieldSet) throws BindException {
final ImportDataObject importDataObject = new ImportDataObject();
importDataObject.setKittenUrl(fieldSet.readString(0));
importDataObject.setKittenName(fieldSet.readString(1));
importDataObject.setNumOfReviews(fieldSet.readInt(2));
importDataObject.setRating(fieldSet.readInt(3));
importDataObject.setCategories(new ArrayList<String>());
for (int i = 4; i < fieldSet.getFieldCount(); i++) {
importDataObject.getCategories().add(fieldSet.readString(i));
}
return importDataObject;
}
}
I have this code which gets info from an other class but I have to add another line other code for every instance object.
public static int giveShipData(String shipName,int Data){
if(shipName.equals("Player")){i = Player.getData(Data);}
return i;
}
Is it possible to have something like:
public static int giveShipData(String shipName,int Data){
i = shipName.getData(Data);
return i;
}
Sorry if I am using the wrong terminology I am self taught and new.
I think you'd better to reconsider your design. If you have a ship name and ship data I assume you must have a Ship class which looks something like this:
public class Ship {
private String name;
private int data;
public Ship(String name, int data) {
this.name = name;
this.data = data;
}
public String getName() {
return name;
}
public int getData() {
return data;
}
}
Besides this class there should be a class like Shipyard:
public class Shipyard {
private Map<String, Ship> shipsByNameMap = new HashMap<String, Ship>();
public void registerShipByName(String name, Ship ship){
shipsByNameMap.put(name, ship);
}
public Ship getShipByName(String name){
return shipsByNameMap.get(name);
}
}
So, at first you invoke shipyard.getShip("Player") method to get ship object, than you can invoke ship.getData() method to retrieve ship data.
You might be able to do something like this...
int[] ships = new int[3]; // 3 ships
public void populateShips(){
for (int i=0;i<ships.length;i++){
ships[i] = giveShipData(shipname,data);
}
}
public int giveShipData(String shipName,int data){
return shipName.getData(data);
}
This would allow you to create any number of ships, just increase the size of the ships[] array to be however many ships you want.
Is this kinda what you're after?
As per your code "shipName" is a string...and it does not have getData() method. And why are you passing Data to the getData()... You could instead write something like this-
i = ClassObj.getData(shipname);
and in the method getData return the info regarding the "shipname".
I have a year object. For now lets say only two years and its getters and setters
private String mYearOne;
private String mYearTwo;
public String getmYearOne() {
return mYearOne; }
public void setmYearOne(String mYearOne) {
this.mYearOne = mYearOne; }
public String getmYearTwo() {
return mYearTwo; }
public void setmYearTwo(String mYearTwo) {
this.mYearTwo = mYearTwo; }
Then each year has three insurance plans. And its getters and setters.
private String healthPlan;
private String carPlan;
private String housePlan;
private String healthPlanTwo;
private String carPlanTwo;
private String housePlanTwo;
public String getHealthPlan() {
return healthPlan; }
public void setHealthPlan(String healthPlan) {
this.healthPlan = healthPlan; }
public String getCarPlan() {
return carPlan; }
public void setCarPlan(String carPlan) {
this.carPlan = carPlan; }
public String getHousePlan() {
return housePlan; }
public void setHousePlan(String housePlan) {
this.housePlan = housePlan; }
public String getHealthPlan() { //For the second year
return healthPlan; }
public void setHealthPlan(String healthPlan) {
this.healthPlan = healthPlan; }
public String getCarPlan() {
return carPlan; }
public void setCarPlan(String carPlan) {
this.carPlan = carPlan; }
public String getHousePlan() {
return housePlan; }
public void setHousePlan(String housePlan) {
this.housePlan = housePlan; }
public String getHealthPlanTwo() {
return healthPlanTwo; }
public void setHealthPlanTwo(String healthPlanTwo) {
this.healthPlanTwo = healthPlanTwo; }
public String getCarPlanTwo() {
return carPlanTwo; }
public void setCarPlanTwo(String carPlanTwo) {
this.carPlanTwo = carPlanTwo; }
public String getHousePlanTwo() {
return housePlanTwo; }
public void setHousePlanTwo(String housePlanTwo) {
this.housePlanTwo = housePlanTwo; }
You will notice the code is bulky. I need to define them in a <list> of year. So that if 10 years are considered, I would have 10 multiplied
by 3 = 30 plans and its getters and setters respectively.
How could this be done?
I think your best bet will be to maintain a count of number of years and arraylists for the insurance plans. This way, you can get the arraylist once and get the insurance plan details for whatever year you actually want. This will be characterized by a single insurance plan arraylist and a single arraylist for years.
private ArrayList mYear;
private ArrayList healthPlan;
private ArrayList carPlan;
private ArrayList housePlan;
public String getHousePlanForYear(String year){
return housePlan.get(mYear.indexOf(year));
}
public void setHousePlanForYear(String housePlan, String year){
this.housePlan.set(mYear.indexOf(year), housePlan);
}
Similarly for the other plans. Of course, all this is assuming that the year is always present and other boundary conditions. Just add your boundary checks in these getters and setters and you will be good to go. :)
I see a design/domain modelling problem here. A person can ideally have multiple "plans" and "riders" attached to each plan. This should clearly be abstracted away properly by creating a "PlanCollection" class or simply maintaining a list of "plans" which all extend/implement a common "Plan" class/interface.
Each plan can have a "plan" duration and a start date. Also, logically, you don't attach plans to "year" but the timeline information is encapsulated in the Plan itself (like start and duration as mentioned above).
Take a look at enums and maps. The enum would specify car, house etc.
You could create a map that takes an enum as key and a List of years as the key. Don't be tempted to create YearThree etc.
On a note of style: if you intend to use m to prefix fields, take the m out of the setter. E.g. setYearOne not setmYearOne.
Choose your types wisely, don't use a String if an int is better.