Reputation: 11
Dog
and Cat
class inherited from the Animal
class and if I want to add in ArrayList
, I use the codes
pets.add(new Dog(name))
How can I find out if a name is used more than once?
I'm looking for something like : pets.contain(...)
Upvotes: 0
Views: 113
Reputation: 40066
Your question is ambiguous.
If you want to find from a list, names that are used more than once, you can do something like
pets.stream()
.collect(Collectors.groupingBy(Animall::getName(), Collectors.counting()))
.entrySet().stream()
.filter(e->e.getValue() > 1)
.map(e->e.getKey())
.collect(Collectors.toList()));
which will give you a List<String>
containing names appeared more than once
If you just want to check if a name exists in pets
before you add to it, I think you should use Map<String, Animal>
instead of a List
.
Upvotes: 0
Reputation: 2112
There isn't a way of doing this with a native function.
You could try the following:
int number = 0;
for (int i=0; i<pets.size(); i++){
if pets.get(i).getname().equalsIgnoreCase("nameYouWant") number++;
}
Upvotes: 0
Reputation: 17445
There is actually a contains method on List. It uses the equals method to check for equality, so if your Dog
or Cat
classes implement equals
in a way that the same name means equality, you can simply use contains
.
If for some reason you don't want to do that (because you need equality to mean something else), you can just iterate over the list and find an entry with the same name. Or alternatively, use a stream, like so: pets.stream().filter(pet -> pet.getName().equals(newName)).findAny().isPresent()
Upvotes: 1
Reputation: 1657
If you are using Java8 you can use something like:
pets.stream().map(animal -> animal.getName()).contains(name);
which will return boolean whether name is already in List.
Another way is using for loop:
boolean isNamePresent = false;
for (Animal pet: pets) {
if(pet.getname().equals(name)) {
isNamePresent = true;
}
}
Upvotes: 0