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

How to efficiently (performance) remove many items from List in Java?

OK, it’s time for test results of proposed approaches. Here what approaches I have tested (name of each approach is also class name in my sources): NaiveRemoveManyPerformer – ArrayList with iterator and remove – first and naive implementation given in my question. BetterNaiveRemoveManyPerformer – ArrayList with backward iteration and removal from end to front. LinkedRemoveManyPerformer … Read more