COUNT UNIQUE ELEMENTS USING HASHSET IN JAVA
//sometimes you may come across requirement to count unique objects.
//In that case one of the solution is to create a hashset field/attribute in the class.
//For eg. animal is a class with name variable. zoo is a class which holds collections of animals.
//so if i want to count unique animals in zoo. i added hashset in the zoo class.
//set is a collection which holds only unique elements. but lists holds duplicate values.
import java.util.ArrayList;
import java.util.HashSet;
class Animal{
String name;
public Animal(String name){
this.name = name;
}
}
class Zoo{
//list of animals present in zoo, multiple animals of same species also present in zoo
ArrayList<Animal> animalList = new ArrayList<Animal>();
//to track unique animals hashset is one of the solution
HashSet<String> uniqueAnimals = new HashSet<String>();
}
public class TestZoo{
public static void main(String[] args){
Animal elephant = new Animal("elephant");
Animal dog = new Animal("dog");
//dog repeated twice
Animal anotherDog = new Animal("dog");
Animal crocodile = new Animal("crocodile");
//crocodile repeated twice
Animal anotherCrocodile = new Animal("crocodile");
//add all animals to zoo
Zoo zoo = new Zoo();
ArrayList<Animal> addAnimalsTOzoo = new ArrayList<Animal>();
addAnimalsTOzoo.add(elephant);
addAnimalsTOzoo.add(dog);
addAnimalsTOzoo.add(anotherDog);
addAnimalsTOzoo.add(crocodile);
addAnimalsTOzoo.add(anotherCrocodile);
zoo.animalList = addAnimalsTOzoo;
//use hashset to count unique animals
HashSet<String> countUniqueAnimals = new HashSet();
countUniqueAnimals.add(elephant.name);
countUniqueAnimals.add(dog.name);
countUniqueAnimals.add(anotherDog.name);
countUniqueAnimals.add(crocodile.name);
countUniqueAnimals.add(anotherCrocodile.name);
zoo.uniqueAnimals = countUniqueAnimals;
System.out.println("unique animals count = "+zoo.uniqueAnimals.size());
}
}
No comments:
Post a Comment