Search code examples
arraysobjectpojoprintlnjava-5

How to print a specific object by field id within an array list of objects?


I have a Location class that stores multiple location objects, parsed in from a JSON file. At the moment I can print out all locations in the list by using the toString() method. The output looks like this:

http://hastebin.com/eruxateduz.vhdl

This is an example of one of the loctions within the list:

Location [location=null, id=3, description=You are at battlefield of Jerusalem. You are in awe of your surroundings, you see an exit to the west., weight=100, name=Jerusalem, exit=[Exit [title=Hattin, direction=West]]], 

But I'm wondering how I can print out a specific location within that list by the field value id, for example the loction with id="2"?

I'm thinking an override toString method could be created to take an input of id, and print the corresponding location object, but not sure how to print by 'id':

if(LocationObject.getId() == "2") {
      //do something
}

This is the POJO Location class that stores the objects:

public class Location {

    private Location[] location;

    private int id;

    private String description;

    private String weight;

    private String name;

    private Exit[] exit;

    private boolean visited = false;
    private boolean goalLocation;
    private int approximateDistanceFromGoal = 0;
    private Location parent;




    public Location[] getLocation() {
        return location;
    }

    public void setLocation(Location[] location) {
        this.location = location;
    }


    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getDescription ()
    {
        return description;
    }

    public void setDescription (String description)
    {
        this.description = description;
    }


    public String getWeight() {
        return weight;
    }

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

    public String getName ()
    {
        return name;
    }

    public void setName (String name)
    {
        this.name = name;
    }

    public Exit[] getExit() {
        return exit;
    }

    public void setExit(Exit[] exit) {
        this.exit = exit;
    }

    @Override
    public String toString() {
        return "Location [location=" + Arrays.toString(location) + ", id=" + id
                + ", description=" + description + ", weight=" + weight
                + ", name=" + name + ", exit=" + Arrays.toString(exit)
                +"]";
    }



}

Solution

  • try checking id's

    if(LocationObject.getId() == "2") {
          System.out.println(LocationObject.getDescription());
    }