Reputation: 3143
I'm used to programming in PHP and now I'm studing Java, and the whole Collections API is a whole new thing for me.
I searched and got to know some ways to iterate over a HashSet, like using:
Source and many others easily found in the internet.
But what's the best way to iterate over it or what's the difference between those, like which one should I use in different scenarios.
Upvotes: 1
Views: 3089
Reputation: 1216
Each has its own benefits and drawbacks. Using the iterator() and Java 8 forEachRemaining() method is not really different from the simple forEach() on the Set itself, but requires one more method to be called.
Using forEach() on the Set with lambda expressions is great, if you want one simple method call on every piece in the set.
the for(T item: someSet) {} is cleaner if you do a lot of things for each piece, or if there are side-effects to the things you do with them.
if there are no side-effects, but let's say you want to search for a specific property or a set of specific properties in the set, I'd suggest using the Stream API, where you can filter(), map(), find, or collect to some other type of collection.
Whatever you use is mainly down to what appeals to you personally. The different ways may be really different in implementation, but they can most of the times do the same things. It mainly comes down to taste or standards in the team
Upvotes: 4
Reputation: 842
If you place lots of objects into Collection and want to iterate though it you should consider using List interface instead because Big-O for iteration is faster for Lists in this situation. Talking about HashSet, it merely depends on your code style and tasks you want to perform on the elements in the HashSet
Upvotes: 0