How to Iterate over a Set/HashSet without an Iterator?
You can use an enhanced for loop: Set<String> set = new HashSet<String>(); //populate set for (String s : set) { System.out.println(s); } Or with Java 8: set.forEach(System.out::println);
You can use an enhanced for loop: Set<String> set = new HashSet<String>(); //populate set for (String s : set) { System.out.println(s); } Or with Java 8: set.forEach(System.out::println);
A list keeps order, dict and set don’t: when you care about order, therefore, you must use list (if your choice of containers is limited to these three, of course 😉 ). dict associates each key with a value, while list and set just contain values: very different use cases, obviously. set requires items to … Read more
Adding the contents of a list Use set.update() or the |= operator: >>> a = set(‘abc’) >>> a {‘a’, ‘b’, ‘c’} >>> xs = [‘d’, ‘e’] >>> a.update(xs) >>> a {‘e’, ‘b’, ‘c’, ‘d’, ‘a’} >>> xs = [‘f’, ‘g’] >>> a |= set(xs) >>> a {‘e’, ‘b’, ‘f’, ‘c’, ‘d’, ‘g’, ‘a’} Adding the … Read more
From Python version 2.6 on you can use multiple arguments to set.intersection(), like u = set.intersection(s1, s2, s3) If the sets are in a list, this translates to: u = set.intersection(*setlist) where *a_list is list expansion Note that set.intersection is not a static method, but this uses the functional notation to apply intersection of the … Read more
See the javadoc of List list.get(0); or Set set.iterator().next(); and check the size before using the above methods by invoking isEmpty() !list_or_set.isEmpty()
To answer the precise question “Why doesn’t Set provide an operation to get an element that equals another element?”, the answer would be: because the designers of the collection framework were not very forward looking. They didn’t anticipate your very legitimate use case, naively tried to “model the mathematical set abstraction” (from the javadoc) and … Read more
The typical way to check for existence in many STL containers such as std::map, std::set, … is: const bool is_in = container.find(element) != container.end();
List is an ordered sequence of elements whereas Set is a distinct list of elements which is unordered (thank you, Quinn Taylor). List<E>: An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their … Read more
your_set.update(your_sequence_of_values) e.g, your_set.update([1, 2, 3, 4]). Or, if you have to produce the values in a loop for some other reason, for value in …: your_set.add(value) But, of course, doing it in bulk with a single .update call is faster and handier, when otherwise feasible.
If you’re using .NET 3.5, you can use HashSet<T>. It’s true that .NET doesn’t cater for sets as well as Java does though. The Wintellect PowerCollections may help too.