Reputation: 10211
Which one should be faster? I need to insert element quickly and also remove duplicates.
Code example:
List catNames = new ArrayList();
for(Cat cat: cats){
catNames.add(nameTheCat(cat));
}
new HashSet(catNames); // remove duplicates finally
vs
HashSet catNames = new HashSet();
for(Cat cat: cats){
catNames.add(nameTheCat(cat));
}
Upvotes: 1
Views: 33
Reputation: 393771
The first snippet (creating the List
first) can be wasteful (both in memory and time) if there are many duplicates, since you are going to eliminate the duplicates later.
Therefore, it makes more sense to use the second snippet, and add the elements directly to the Set
.
EDIT: after changing your question, you can shorten your code by using Stream
s:
Set<String> catNames = cats.map(cat->nameTheCat(cat)).collect(Collectors.toSet());
Upvotes: 1