nonope nonope - 3 months ago 14
Java Question

Retrieve and Iterate map class database in Java

I have the following class files below

Database Class

public class DBClass {

private static Map<Long, Fish> fishs= new HashMap<>();

public static Map<Long, Fish> getFishs(){
return fishs;
}
}


Fish Class

public class Fish{

private long id;
private String fishName;
private String descr; //description
private double weight;
private String fishLoc; //location

public Fish(){

}

public Fish(long id,String fishName,String descr,double weight,String fishLoc){
this.id = id;
this.fishName= fishName;
this.descr = descr;
this.weight= weight;
this.fishLoc = fishLoc;
}

public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}

public String getFishName() {
return fishName;
}

public void setFishName(String fishName) {
this.fishName= fishName;
}

public String getDescr() {
return descr;
}

public void setDescr(String descr) {
this.descr = descr;
}

public double getWeight() {
return weight;
}

public void setWeight(double weight) {
this.weight = weight ;
}

public String getFishLoc() {
return fishLoc;
}

public void setFishLoc(String fishLoc) {
this.fishLoc = fishLoc;
}

}


FishServ Class

public class FishServ {

private Map<Long, Fish> fishDB = DatabaseClass.getFishs();

public FishServ (){

fishDB.put(1L,new Fish(1,"Starfish","Shape like a star",5.25,"Atlantic Ocean"));
fishDB.put(2L,new Fish(2,"Salmon","Looks like dinner",3.25,"Pacific Ocean"));
fishDB.put(3L,new Fish(3,"Sardines","Plenty to go around",0.05,"Rainfall"));
}

public List<Fish> getAllFishs(){
return new ArrayList<Fish>(fishDB.values());
}
}


DatabaseTest Class (Not Working)

public class DBTest{
private static Map<Long, Fish> fishDB = DatabaseClass.getFishs();

public static void main(String[] args){
Iterator entries = fishDB.entrySet().iterator();
while (entries.hasNext()) {
Entry thisEntry = (Entry) entries.next();
Object key = thisEntry.getKey();
Object value = thisEntry.getValue();
}

System.out.println("FAILED BIG TIME");
}
}


There was no output and no error,
I don't know how to iterate through this Database map, I attempted at DatabaseTest but it didn't work out.

What I want to do is iterate through the database id and retrieve the value object then separate the value object up into e.g. fishName, description, etc. and assign each variable to them for DatabaseTest class.

Answer

In your test you never populate the database map with anything. So if it's empty your loop will not run.

If you actually use your FishServ class, then you could just get the list that you are returning in getAllFishs() and iterate over that like so:

FishServ fishServ = new FishServ();
List<Fish> fishList = fishServ.getAllFishs();
for (Fish fish in fishList) {
    // Process fish and get contents, description, etc.
}