3

I have two classes Dog.java and DogSerach.java and I want to print dog detail using HashMap. I studied duplicate of this question get string value from HashMap depending on key name and also studied Oracle doc http://docs.oracle.com/javase/tutorial/collections/interfaces/map.html, but still can not figure it out.

I have tried in DogSearch.java

for (String key: dogs.keySet()) {
            System.out.println("Registration number : " + key);
           System.out.println("Detail : " +  dogs.get(key));
           }

But I get

Registration number : 1003
Detail : Dog [name=Luca, breed=Labrador, registrationNumber=1003]
Registration number : 1002
Detail : Dog [name=Gracie, breed=Rottweiler, registrationNumber=1002]
Registration number : 1001
Detail : Dog [name=Max, breed=German Shepherd, registrationNumber=1001]

I want to print like this

Registration number: 1001
Name: Max
Breed: German Shepherd
... etc. 

DogSearch.java

public class DogSearch {

    static Scanner scanner = new Scanner(System.in);
    public static void main(String[] args) {
        Map<String, Dog> dogs = new HashMap<String, Dog>();

        Dog max = new Dog("Max", "German Shepherd", "1001");
        Dog gracie = new Dog("Gracie", "Rottweiler", "1002");
        Dog luca = new Dog("Luca", "Labrador", "1003");


        dogs.put(max.getRegistrationNumber(), max);
        dogs.put(gracie.getRegistrationNumber(), gracie);
        dogs.put(luca.getRegistrationNumber(), luca);


        System.out.println("List of dogs by name: ");

        for (String key: dogs.keySet()) {
            System.out.println("Registration number : " + key);
            System.out.println("Breed : " +  dogs.get(key));

        }

    }
}

Dog.java

class Dog {
    private String name;
    private String breed;
    private String registrationNumber;

    public Dog(String name, String breed, String registrationNumber) {
        this.name = name;
        this.breed = breed;
        this.registrationNumber = registrationNumber;
    }


    public String getName() {
        return name;
    }

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

    public String getBreed() {
        return breed;
    }

    public void setBreed(String breed) {
        this.breed = breed;
    }

    public String getRegistrationNumber() {
        return registrationNumber;
    }

    public void setRegistrationNumber(String registrationNumber) {
        this.registrationNumber = registrationNumber;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((breed == null) ? 0 : breed.hashCode());
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        result = prime * result + ((registrationNumber == null) ? 0 : registrationNumber.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Dog other = (Dog) obj;
        if (breed == null) {
            if (other.breed != null)
                return false;
        } else if (!breed.equals(other.breed))
            return false;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        if (registrationNumber == null) {
            if (other.registrationNumber != null)
                return false;
        } else if (!registrationNumber.equals(other.registrationNumber))
            return false;
        return true;
    }

    @Override
    public String toString() {
        return "Dog [name=" + name + ", breed=" + breed + ", registrationNumber=" + registrationNumber + "]";
    }
}
4
  • Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See: How to create a minimal reproducible example. Use the "edit" link to improve your question - do not add more information via comments. Thanks! Commented Sep 4, 2017 at 17:52
  • nothing to searching, but printing Commented Sep 4, 2017 at 17:55
  • I received output as [name=Gracie, breed=Rottweiler, registrationNumber=1002] but I want to get with separate one like Name is: Gracie, Breed is Rottweiler and registrationNumber is 1002. Commented Sep 4, 2017 at 17:55
  • Hint: never put more information into comments. Always update your question instead! Commented Sep 4, 2017 at 18:50

3 Answers 3

2

You can just do:

for (String key: dogs.keySet()) {
        System.out.println("Registration number : " + key);
        System.out.println("Name: " +  dogs.get(key).getName());
        System.out.println("Breed: " +  dogs.get(key).getBreed());
       }
   }

With Java 8 streams you can sort the map by the names of your dogs.

Map<String, Dog> result = dogs.entrySet().stream() 
      .sorted(Map.Entry.comparingByValue(new MyComparator())) 
      .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, 
           (oldValue, newValue) -> oldValue, LinkedHashMap::new)); 

and then loop through the result map.

for (String key: result.keySet()) {
    System.out.println("Registration number : " + key);
     System.out.println("Name: " +  dogs.get(key).getName());
     System.out.println("Breed: " +  dogs.get(key).getBreed());
   }

}

And you need a Comparator class

public class MyComparator implements Comparator<Dog>{ 

     public int compare(Dog s1, Dog s2) { 
          return s1.getName().compareTo(s2.getName()); 
     } 
 }
Sign up to request clarification or add additional context in comments.

2 Comments

Is there any way I can print the list of dogs by name. I mean printing list sorted by name?
There are many ways, but you can check this link java2s.com/Tutorials/Java/Collection_How_to/Map/…
1

There are multiple ways to achieve what you want:

The first one is to change the toString() method of your Dog.java. When using System.out.println(), java uses the toString() method when passing classes as arguments. So changing your toString() to :

return "Name: " + name + "\n" + 
       "Breed: " + breed;

should do the trick.

The second way is to change what you print in your for loop. an example of what you can do is:

for (String key: dogs.keySet()) {
    System.out.println("Registration number : " + key);
    Dog dog = dogs.get(key);
    System.out.println("Name : " +  dog.getName());
    System.out.println("Breed: " +  dog.getBreed());
}

Comments

0

why don't you create a method in class Dog and write the implementation the way would like to print!

So here you just need

for (String key: dogs.keySet()) {
    System.out.println(dogs.get(key).getPrintString());

}

This will go in Dog class

public String getPrintString() { 
 return "Registration number : "+ getRegistrationNumber() +"\nName: " +getName() +"\nBreed:"+getBreed(); // This can be optimized further using StringBuffer
}

7 Comments

Like in` @Override public String toString() { return "Dog ` which I just copied from his code?
toString() in general is not for printing in applications, but for short displaying, debug info etc. Sometimes is used, but only in simplest cases
I guess, in above scenario, it fits the puprose!
And when application code wants to change order, add wihitespace etc? Agree this is used, but not recomended
I guess, user is not using toString method anywhere else, so I still recommend to use it rather than printing whole lots of sysout messages.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.