简体   繁体   English

从HashMap打印值列表

[英]Print list of values from HashMap

I have two classes Dog.java and DogSerach.java and I want to print dog detail using HashMap. 我有两个类Dog.javaDogSerach.java ,我想使用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. 我研究了根据密钥名称从HashMap获取字符串值的该问题的副本,还研究了Oracle doc http://docs.oracle.com/javase/tutorial/collections/interfaces/map.html ,但仍无法弄清楚。

I have tried in DogSearch.java 我已经在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 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 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 + "]";
    }
}

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. 使用Java 8流,您可以按狗的名称对地图进行排序。

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 而且您需要一个Comparator类

public class MyComparator implements Comparator<Dog>{ 

     public int compare(Dog s1, Dog s2) { 
          return s1.getName().compareTo(s2.getName()); 
     } 
 }

There are multiple ways to achieve what you want: 有多种方法可以实现您想要的:

The first one is to change the toString() method of your Dog.java . 第一个是更改Dog.javatoString()方法。 When using System.out.println() , java uses the toString() method when passing classes as arguments. 使用System.out.println() ,java在将类作为参数传递时使用toString()方法。 So changing your toString() to : 因此,将toString()更改为:

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

should do the trick. 应该可以。

The second way is to change what you print in your for loop. 第二种方法是更改​​for循环中的打印内容。 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());
}

why don't you create a method in class Dog and write the implementation the way would like to print! 您为什么不在Dog类中创建一个方法并以想要打印的方式编写实现!

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM