【发布时间】:2020-08-13 02:23:45
【问题描述】:
我创建了一个带有 String 品种和 int ageinmonths 的 Dog 类。
String breed;
int ageInMonths;
public String getBreed() {
return breed;
}
public void setBreed(String breed) {
this.breed = breed;
}
public int getAgeInMonths() {
return ageInMonths;
}
public void setAgeInMonths(int ageInMonths) {
this.ageInMonths = ageInMonths;
}
public Dog(String breed, int ageInMonths) {
this.breed = breed;
this.ageInMonths = ageInMonths;
}
public String toString() {
return this.getBreed()+" - Age : "+
this.getAgeInMonths()+" - Count : ";
}
在主要方法中,我使用了比较器。
public static void main(String[] args) {
Dog dog1 = new Dog("Companion", 10);
Dog dog2 = new Dog("Herding", 4);
Dog dog3 = new Dog("Terrier", 15);
Dog dog4 = new Dog("Companion", 7);
Dog dog5 = new Dog("Terrier", 15);
Dog dog6 = new Dog("Terrier", 9);
Dog dog7 = new Dog("Herding", 10);
Dog dog8 = new Dog("Herding", 10);
TreeMap<Integer, Dog> dogDetails = new TreeMap<Integer, Dog>();
dogDetails.put(1, dog1);
dogDetails.put(2, dog2);
dogDetails.put(3, dog3);
dogDetails.put(4, dog4);
dogDetails.put(5, dog5);
dogDetails.put(6, dog6);
dogDetails.put(7, dog7);
dogDetails.put(8, dog8);
System.out.println("The dog details are given below : "+dogDetails);
}
@Override
public int compare(Dog dog1, Dog dog2) {
return dog1.breed.compareTo(dog2.breed);
}
但是我怎样才能得到唯一对象的数量。我想要如下所述的输出: 同伴 - 年龄 : 10 - 人数 : 1 放牧 - 年龄:10 - 计数:2
【问题讨论】:
-
你能给出可能的输入,以及相应的输出吗?
-
已经提到了输出(最后一行有问题)-同伴-年龄:10-计数:1放牧-年龄:10-计数:2。对于剩余的品种也是如此。在 main 方法中提到了输入。
-
做一些研究,例如对
java group count进行网络搜索,您会发现许多 示例说明如何执行此操作。 -
@Dinu 既然只比较
breed,那你想对不同年龄做些什么呢?例如。Companion - Age : 7呢? -
@Andreas- 是的,还应该比较不同的年龄。我会检查链接。谢谢
标签: java collections comparator treemap