Я создал класс Dog со String breed и int ageinmonths.
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