guo
guo

Reputation: 10211

Insert Performance: Use HashSet at begin vs use ArrayList at begin and use hashset to remove duplicate at the end

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

Answers (1)

Eran
Eran

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 Streams:

Set<String> catNames = cats.map(cat->nameTheCat(cat)).collect(Collectors.toSet());

Upvotes: 1

Related Questions