Immutable version of EnumSet

Are you looking for Sets.immutableEnumSet (Guava) perhaps? Returns an immutable set instance containing the given enum elements. Internally, the returned set will be backed by an EnumSet. The iteration order of the returned set follows the enum’s iteration order, not the order in which the elements appear in the given collection.

How to convert defaultdict of defaultdicts [of defaultdicts] to dict of dicts [of dicts]?

You can recurse over the tree, replacing each defaultdict instance with a dict produced by a dict comprehension: def default_to_regular(d): if isinstance(d, defaultdict): d = {k: default_to_regular(v) for k, v in d.items()} return d Demo: >>> from collections import defaultdict >>> factory = lambda: defaultdict(factory) >>> defdict = factory() >>> defdict[‘one’][‘two’][‘three’][‘four’] = 5 >>> defdict … Read more

Collection class that doesn’t allow null elements?

Use Constraints: import com.google.common.collect.Constraints; … Constraints.constrainedList(new ArrayList(), Constraints.notNull()) from Guava for maximum flexibility. UPDATE: Guava Constraints has been deprecated in Release 15 – apparently without replacement. UPDATE 2: As of now (Guava 19.0-rc2) Constrains is still there and not deprecated anymore. However, it’s missing from the Javadoc. I’m afraid that the Javadoc is right as … Read more

Get the last element of a Java collection

A Collection is not a necessarily ordered set of elements so there may not be a concept of the “last” element. If you want something that’s ordered, you can use a SortedSet/NavigableSet which has a last() method. Or you can use a List and call mylist.get(mylist.size()-1); If you really need the last element you should … Read more

Getting list of currently active managed threads in .NET?

If you’re willing to replace your application’s Thread creations with another wrapper class, said wrapper class can track the active and inactive Threads for you. Here’s a minimal workable shell of such a wrapper: namespace ThreadTracker { using System.Collections.Generic; using System.Collections.ObjectModel; using System.Threading; public class TrackedThread { private static readonly IList<Thread> threadList = new List<Thread>(); … Read more

Why and when to use TreeMap

Let’s say you want to implement a dictionary and print it in alphabetical order, you can use a combination of a TreeMap and a TreeSet: public static void main(String args[]) { Map<String, Set<String>> dictionary = new TreeMap<>(); Set<String> a = new TreeSet<>(Arrays.asList(“Actual”, “Arrival”, “Actuary”)); Set<String> b = new TreeSet<>(Arrays.asList(“Bump”, “Bravo”, “Basic”)); dictionary.put(“B”, b); dictionary.put(“A”, a); … Read more