打印hashmap中的值列表

cig3rfwq  于 2021-07-03  发布在  Java
关注(0)|答案(3)|浏览(339)

我有两节课 Dog.java 以及 DogSerach.java 我想用hashmap打印狗的细节。我研究了这个问题的副本,根据键名从hashmap中获取字符串值,还研究了oracle文档http://docs.oracle.com/javase/tutorial/collections/interfaces/map.html,但还是想不通。
我在dogsearch.java中尝试过

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

但我明白了

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]

我想印成这样

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

狗搜索.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));

        }

    }
}

狗.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 + "]";
    }
}
j9per5c4

j9per5c41#

有多种方法可以实现您的目标:
第一个是改变现状 toString() 你的方法 Dog.java . 使用时 System.out.println() ,java使用 toString() 方法将类作为参数传递。所以改变你的生活 toString() 收件人:

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

应该会成功的。
第二种方法是更改for循环中打印的内容。你可以做的一个例子是:

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());
}
y1aodyip

y1aodyip2#

你可以这样做:

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());
       }
   }

使用Java8流,您可以按狗的名字对Map进行排序。

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));

然后在结果图中循环。

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());
   }

}
你需要一个比较类

public class MyComparator implements Comparator<Dog>{ 

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

bejyjqdl3#

为什么不在dog类中创建一个方法,并按照您希望打印的方式编写实现呢!
所以你只需要

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

}

这将在狗课上进行

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

相关问题