简体   繁体   English

在Java中迭代HashSet的最佳方法

[英]Best way to iterate over HashSet in Java

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. 我习惯于使用PHP进行编程,现在学习Java,整个Collections API对我来说都是全新的东西。

I searched and got to know some ways to iterate over a HashSet, like using: 我进行搜索并了解了一些遍历HashSet的方法,例如使用:

  • Java 8 forEach and lambda expression. Java 8 forEach和lambda表达式。
  • iterator(). iterator()。
  • iterator() and Java 8 forEachRemaining() method. iterator()和Java 8 forEachRemaining()方法。
  • simple for-each loop. 简单的for-each循环。

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. 但是最好的迭代方法是什么,或者两者之间的区别是什么,例如我应该在不同的情况下使用哪种方法。

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. 在set本身上使用iterator()和Java 8 forEachRemaining()方法与简单的forEach()并没有真正的区别,但是还需要调用另一种方法。

Using forEach() on the Set with lambda expressions is great, if you want one simple method call on every piece in the set. 如果要对集合中的每一部分进行一个简单的方法调用,请在具有lambda表达式的Set上使用forEach()很棒。

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. 如果您为每一件事情做很多事情,或者您对它们所做的事情有副作用,那么for(T item:someSet){}会更干净。

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. 如果没有副作用,但是假设您要在集合中搜索特定属性或一组特定属性,我建议使用Stream API,您可以在其中进行filter(),map(),查找,或收集到其他某种类型的集合。

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 它主要取决于团队中的品味或标准

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. 如果将大量的对象转换成 ,并希望迭代虽然你应该考虑使用List接口,而不是因为大O迭代是在这种情况下更快列表 Talking about HashSet , it merely depends on your code style and tasks you want to perform on the elements in the HashSet 在谈论HashSet时 ,它仅取决于您的代码样式和要在HashSet中的元素上执行的任务

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM